基于键合并两个对象数组而不展平它?

时间:2019-04-01 08:40:28

标签: javascript arrays ecmascript-6

这篇文章就像是续篇  发表Merge two array of objects based on a key我喜欢@Trevors https://stackoverflow.com/a/51672402/9215279的答案,但是如何合并数组而不使其变平?

更新的代码

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)) 

输出

[
  {
    "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"
      }
    }
  }
]

您能建议如何输出吗?

[
  {
    "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"
      }
    }
  }
]

3 个答案:

答案 0 :(得分:1)

您可以使用array#map遍历每个用户,并通过比较array#finduserId使用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);

答案 1 :(得分:0)

尝试一下:

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));

没有flattening的合并只是键上运行的另一个循环。

答案 2 :(得分:-2)

您可以这样做:

arr1.map(row=>{
    const found = arr1.find(item=>item.id==row.id);
    return Object.assign({}, row, found);
});
相关问题