Skip to content
Advertisement

Map two separate arrays by matching object keys to values

Been scratching my head on this one for an entire evening with no solution in sight.

Put simply

I am querying two arrays from two separate APIs.

They return data in following format:

API 1

[{
  balance: 4444,
  age: "18",
  gender: "Male",
  level: "2",
  name: "Joe"
  
}, {
  balance: 3333,
  age: "45",
  gender: "Male",
  level: "3",
  name: "Angel"
}
}]

API 2

{
  Joe: {
    score: 32
  },
  Angel: {
    score: 22
  }
}

I need to match the object keys from the second API to the name value of playerInfo from first API so a new array is made that is completely flat like this:

[{
  balance: 4444,
  age: "18",
  gender: "Male",
  level: "2",
  name: "Joe",
  score: 32
  
}, {
  balance: 3333,
  age: "45",
  gender: "Male",
  level: "3",
  name: "Angel",
  score: 22
}
}]

Here’s where I am being stone walled at the moment

var result = []

const matchKeys = (data, data1) => {    
  let arr = []
  arr.push(data1)

  data.map(item => {
    arr.map(item1 => {
      if (item.name === Object.keys(item1)) {
        result.push(Object.assign(item, item1))
        console.log(result)
      }
    })
  })
}

matchKeys(api1, api2)

I suspect I’m not getting very far because I am not properly accessing my second dataset because there is no index that keeps track of which object I am supposed to pair up with corresponding value in the arrays.

Appreciate any help

Advertisement

Answer

You can implement that using Array.map.

const input1 = [{
  balance: 4444,
  age: "18",
  gender: "Male",
  level: "2",
  name: "Joe"
}, {
  balance: 3333,
  age: "45",
  gender: "Male",
  level: "3",
  name: "Angel"
}];

const input2 = {
  Joe: {
    score: 32
  },
  Angel: {
    score: 22
  }
}

function matchKeys(arr1, arr2) {
  const result = arr1.map((item) => {
    if (input2[item.name]) {
      return { ...item, ...input2[item.name] };
    }
    return item;
  });
  return result;
}

console.log(matchKeys(input1, input2));
Advertisement