-1

This post is like a continuation to this post Merge two array of objects based on a key I like @Trevors https://stackoverflow.com/a/51672402/9215279 answer but How do you merge arrays without flattening it?

Updated code

const users = [
    {
        id: 1,
        name: 'Leanne Graham',
        username: 'Bret',
        email: 'Sincere@april.biz',
        address: {
            street: 'Kulas Light',
            suite: 'Apt. 556',
            city: 'Gwenborough',
            zipcode: '92998-3874',
            geo: {
                lat: '-37.3159',
                lng: '81.1496'
            }
        }
    }
]

const posts = [
    {
        userId: 1,
        id: 1,
        title:
            'sunt aut facere repellat provident occaecati excepturi optio reprehenderit',
        body:
            'quia et suscipit suscipit recusandae consequuntur expedita et cum reprehenderit molestiae ut ut quas totam nostrum rerum est autem sunt rem eveniet architecto'
    }
]

const mergeById = (a1, a2) =>
    a1.map(itm => ({
        ...a2.find((item) => (item.id === itm.id) && item),
        ...itm
    }));

console.log(mergeById(users, posts)) 

Output

[
  {
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "quia et suscipit suscipit recusandae consequuntur expedita et cum reprehenderit molestiae ut ut quas totam nostrum rerum est autem sunt rem eveniet architecto",
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "Sincere@april.biz",
    "address": {
      "street": "Kulas Light",
      "suite": "Apt. 556",
      "city": "Gwenborough",
      "zipcode": "92998-3874",
      "geo": {
        "lat": "-37.3159",
        "lng": "81.1496"
      }
    }
  }
]

Can you suggest how to output like this ?

[
  {
    "posts": {
        "userId": 1,
            "id": 1,
            "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
            "body": "quia et suscipit suscipit recusandae consequuntur expedita et cum reprehenderit molestiae ut ut quas totam nostrum rerum est autem sunt rem eveniet architecto"
        },
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "Sincere@april.biz",
    "address": {
      "street": "Kulas Light",
      "suite": "Apt. 556",
      "city": "Gwenborough",
      "zipcode": "92998-3874",
      "geo": {
        "lat": "-37.3159",
        "lng": "81.1496"
      }
    }
  }
]
devjson
  • 113
  • 2
  • 16

3 Answers3

1

You can iterate through each user using array#map and find the posts using array#find by comparing the userId and id.

const users = [ { id: 1, name: 'Leanne Graham', username: 'Bret', email: 'Sincere@april.biz', address: { street: 'Kulas Light', suite: 'Apt. 556', city: 'Gwenborough', zipcode: '92998-3874', geo: { lat: '-37.3159', lng: '81.1496' } } } ],
      posts = [ { userId: 1, id: 1, title: 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit', body: 'quia et suscipit suscipit recusandae consequuntur expedita et cum reprehenderit molestiae ut ut quas totam nostrum rerum est autem sunt rem eveniet architecto' } ],
      result = users.map(o => ({posts: posts.find(o => o.userId === o.id), ...o}));
console.log(result);
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
0

Try this:

const mergeById = (...arrays) => {
  const unique = {};
  arrays.map(arr => {
    arr.map(val => {
      if (!unique[val.id]) {
        unique[val.id] = val;
        return;
      }
      for (var keys in unique[val.id]) {
        unique[val.id][keys] = unique[val.id][keys] || val[keys]
      }
  });
  return Object.values(unique);
}

console.log(mergeById(array1, array2, ....., arrayN));

Merging without flattening is just another loop running on the keys.

varun agarwal
  • 1,491
  • 6
  • 9
-2

You can do this:

arr1.map(row=>{
    const found = arr1.find(item=>item.id==row.id);
    return Object.assign({}, row, found);
});
sarkiroka
  • 1,485
  • 20
  • 28