首页 > 解决方案 > 根据 id 将数组中的 n 个对象合并为一个数组

问题描述

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

我尝试使用reduce方法,但我无法理解我做错了什么,对于高级js方法仍然很陌生。

  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;
    }, {})
  );

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

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

标签: javascriptarrayssortingreduce

解决方案


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


推荐阅读