根据ID将数组中的n个对象合并到一个数组中 [英] Merge n object from array into one array based on id

查看:195
本文介绍了根据ID将数组中的n个对象合并到一个数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试合并下面列出的对象数组中的n个对象.

I'm trying to merge n objects from an array of objects listed below.

我尝试使用reduce方法,但是我不明白自己在做什么错,仍然是提高js方法的新手.

I tried to use reduce method, but I can't understand what I'm doing wrong, still new to advance js methods.

  const array = [
    {
      data: {
        '1': {
          foo: 'bar',
          test: true
        },
        '4': {
          foo: 'boor'
        }
      }
    },
    {
      data: {
        '1': {
          x: 'o',
          test2: false
        }
      }
    }
  ];

  const result = Object.values(
    array.reduce((r, { data }) => {
      Object.entries(data).forEach(([id, { ...else }]) => {
        r[id] = r[id] || {
          id,
          fooValue: else.foo, // edited
          x: else.x, // should be undefined for id `4`
          ...else
        };
      });
      return r;
    }, {})
  );

我试图最终得到这样的东西,但是我很迷茫.

I'm trying to get something like this in a end, but I'm pretty lost.

  [
    {
      id: '1',
      foo: 'bar',
      test: true,
      x: 'o',
      test2: false
    },
    {
      id: '4',
      foo: 'boor'
    }
  ]

推荐答案

在您的代码中,如果您已经有r[id],则没有分配其余值.因此,请像这样更改它:

In your code, if you already have a r[id], you didn't assign the rest values. So change it like this:

const result = Object.values(
  array.reduce((r, { data }) => {
    Object.entries(data).forEach(([id, { ...el }]) => {
      r[id] = {
        ...r[id], // this is the point
        id,
        ...el
      };
    });
    return r;
  }, {})
);

这篇关于根据ID将数组中的n个对象合并到一个数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆