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