根据ID将n个对象从数组合并到一个数组 [英] Merge n amount of objects from array into one array based on id

查看:226
本文介绍了根据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, // should be `bar` for id `1` and `boor` for id `4`
          xValue: else.x, // should be `o` for id `1` and `undefined` for id `4`
          all: ...else
        };
      });
      return r;
    }, {})
  );

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

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

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

推荐答案

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

let result = Object.values(array.reduce((acc, c) => {
	let list = Object.entries(c.data);
	list.map( o => {
		let key = o[0];
		acc[key] = (acc[key] || {});
		acc[key]['id'] = key;
		acc[key]['fooValue'] = o[1]['foo'];
		acc[key]['xValue'] = o[1]['x'];
		acc[key]['all'] = {...acc[key]['all'], ...o[1]};
     });
	return acc;

}, {}));

console.log(result);

//or 

let result1 = Object.values(array.reduce((acc, c) => {
let list = Object.entries(c.data);
list.map( o => {
	let key = o[0];
	let value = o[1];
	acc[key] = (acc[key] || {});
	acc[key] = {
		id: key,
		fooValue: value['foo'],
		xValue: value['x'],
		all: {...acc[key]['all'], ...o[1]}
	}
 });
return acc;

}, {}));

console.log(result1);

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

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