Merge n amount of objects from array into one array based on id [duplicate]

醉酒当歌 提交于 2019-12-08 15:23:04

问题


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

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'
      }
    }
  ]

回答1:


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



回答2:


else is a keyword in Javascript. You cannot use it as a variable. Besides, you should wrap the variable with spread operator with curly braces so as to copy the object

const result = Object.values(
  array.reduce((r, { data }) => {
    Object.entries(data).forEach(([id, rest ]) => {
      r[id] = r[id] || {
        id: id,
        fooValue: rest.foo, 
        xValue: rest.x,
        all: rest
      };
    });
    return r;
  }, {})
);


来源:https://stackoverflow.com/questions/58966997/merge-n-amount-of-objects-from-array-into-one-array-based-on-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!