Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map over two arrays of objects, match properties and store specific info in a new array

New to javascript and trying to learn! I am trying to map through two array of objects, and if a certain property matches, pull in specific information into an array.

let result;

let arrNames = [{
  name: "A"
}, {
  name: "B"
}, {
  name: "C"
}]

let arrInfo = [{
  name: "A",
  info: "AAA"
}, {
  name: "B",
  info: "BBB"
}, {
  name: "C",
  info: "ccc"
}]

If arrNames.name == arrInfo.name, I would like result to equal arrInfo.info.

What I've tried:

arrNames.map(x => {
if(arrNames.name == arrInfo.name){
   result=arrInfo.info
}

^ This obviously doesn't work -- but I'm wondering if Assign or Filter would be appropriate.

Thanks in advance for your help (apologies that this is probably a dupe)!

like image 303
BWeb303 Avatar asked Oct 11 '19 19:10

BWeb303


1 Answers

You can use find() inside map() to find the element. This finds the element even if they aren't at the same index in both arrays.

Then use filter() to filter any undefined values which will be present if there isn't a match.

var arrNames = [
   {name: "A"},
   {name: "B"},
   {name: "C"}
];

var arrInfo = [
   {name: "A", info: "AAA"},
   {name: "B", info: "BBB"},
   {name: "C", info: "ccc"}
];

let result = arrNames.map(x => {
  item = arrInfo.find(item => item.name === x.name);
  if (item) { 
    return item.info;
  }      
}).filter(item => item !== undefined); // Can also use filter(item => item);

console.log(result);
like image 87
Nikhil Avatar answered Sep 28 '22 06:09

Nikhil