2

I have two arrays that contain objects. Objects on the first array contain an id, name and age.

I have tried many answers that I have found on StackOverflow such as this one and this one and elsewhere online, however it is proving quite tricky and I am unable to get this working.

var arrOne = [
  {id: 1, name: 'Raul', age: 18},
  {id: 2, name: 'Sarah', age: 20},
  {id: 3, name: 'Sanchez', age: 30}
];

The second array contains an id that is related to the users in the first array and and an associated image.

var arrOne = [
  {id: 1, image: 'raulrod.jpg'},
  {id: 2, image: 'saz.jpg'},
  {id: 1, image: 'hola.jpg'},
  {id: 3, image: 'qtal.jpg'},
  {id: 1, image: 'senor.jpg'},
  {id: 3, image: 'ciao.jpg'},
];

After they are combined I am looking for a result like this with each object combining the objects in both arrays based on the id.

var finalArr = [
  {id: 1, name: 'Raul', age: 18 image: 'raulrod.jpg'},
  {id: 1, name: 'Raul', age: 18 image: 'hola.jpg'},
  {id: 1, name: 'Raul', age: 18 image: 'senor.jpg'},
  {id: 2, name: 'Raul', age: 20 image: 'saz.jpg'}
  {id: 3, name: 'Raul', age: 30 image: 'ciao.jpg'},
  {id: 3, name: 'Raul', age: 30 image: 'qtal.jpg'},
];
Blackus
  • 6,883
  • 5
  • 40
  • 51

3 Answers3

2

With plain ES6, you could map the a new object with the properties of arrOne and, with Array#find, the properties of the related object of arrTwo.

If needed, you could later sort the result by id.

var arrOne = [{ id: 1, name: 'Raul', age: 18 }, { id: 2, name: 'Sarah', age: 20 }, { id: 3, name: 'Sanchez', age: 30 }],
    arrTwo = [{ id: 1, image: 'raulrod.jpg' }, { id: 2, image: 'saz.jpg' }, { id: 1, image: 'hola.jpg' }, { id: 3, image: 'qtal.jpg' }, { id: 1, image: 'senor.jpg' }, { id: 3, image: 'ciao.jpg' }],
    result = arrTwo.map(a => Object.assign({}, a, arrOne.find(b => a.id === b.id)));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

You can use array.map and array.find proptotypes:

var arrOne = [
    {id: 1, name: 'Raul', age: 18},
    {id: 2, name: 'Sarah', age: 20},
    {id: 3, name: 'Sanchez', age: 30}
];

var arrTwo = [
    {id: 1, image: 'raulrod.jpg'},
    {id: 2, image: 'saz.jpg'},
    {id: 1, image: 'hola.jpg'},
    {id: 3, image: 'qtal.jpg'},
    {id: 1, image: 'senor.jpg'},
    {id: 3, image: 'ciao.jpg'}
];
var finalArr = arrTwo.map(item => {
    var correspondingObj = arrOne.find(obj => obj.id === item.id)
    item.name = correspondingObj.name;
    item.age = correspondingObj.age;
    return item;
});
console.log(finalArr);
Faly
  • 13,291
  • 2
  • 19
  • 37
0

Actually, https://stackoverflow.com/a/19480257/5809250 should help you.
Have you included underscore - http://underscorejs.org/#extend?
If you do not want to include underscore, you may use [assign][3] function.

Also, I wrote the example. It is not so perfect so you may try to improve it by yourself.

young B
  • 127
  • 1
  • 11