cup_of
cup_of

Reputation: 6697

Add property from one array into another array with the same key

Instead of explaining the problem in words, I've just made a quick visual representation below.

Say I have the following array:

let arr1 = [
  {
    id: 1,
    someKey: someValue
  },
  {
    id: 2,
    someKey: someValue
  },
]

and another array:

let arr2 = [
  {
    id: 1,
    numberOfItems: 10
  },
  {
    id: 2,
    numberOfItems: 20
  },
]

How would I create the following array?

let result = [
  {
    id: 1,
    someKey: someValue,
    numberOfItems: 10
  },
  {
    id: 2,
    someKey: someValue,
    numberOfItems: 10
  },
]

So as you can see, both arrays have the same id value. I want to take numberOfItems: 10 from the second array and place it into the first array under the same id.

Note: the two ids are completely different, have different properties and length. The only similarity is the id

Upvotes: 2

Views: 1841

Answers (2)

Mohammed Ashfaq
Mohammed Ashfaq

Reputation: 3426

let arr1 = [
  {
    id: 1,
    someKey: 3
  },
  {
    id: 2,
    someKey: 6
  },
];

let arr2 = [
  {
    id: 1,
    numberOfItems: 10
  },
  {
    id: 2,
    numberOfItems: 20
  },
];

let idToNumberOfItem = {};
arr2.forEach(({id, numberOfItems})=> idToNumberOfItem[id]=numberOfItems)

arr1.forEach((item)=> item['numberOfItems'] =  idToNumberOfItem[item.id])

console.log(arr1);

Upvotes: 0

slider
slider

Reputation: 12990

You could first create a map with id as key and then combine the objects This would solve the problem in O(n):

let arr1 = [
  {
    id: 1,
    someKey: 3
  },
  {
    id: 2,
    someKey: 6
  },
];

let arr2 = [
  {
    id: 1,
    numberOfItems: 10
  },
  {
    id: 2,
    numberOfItems: 20
  },
];

let arr2Map = arr2.reduce((acc, curr) => {
  acc[curr.id] = curr
  return acc;
}, {});
let combined = arr1.map(d => Object.assign(d, arr2Map[d.id]));
console.log(combined);

Upvotes: 4

Related Questions