javascript - 根据 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'
}
}
]
解决方案
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);
推荐阅读
- google-cloud-platform - 如何从谷歌云下载 NYC-TLC-GREEN_2015/2014 公共数据集到我的本地系统?
- excel - 指数公式excel
- forms - 在 Web 表单中保存项目列表的正确方法是什么?
- google-chrome-extension - 允许在 chrome 扩展上混合 http over https
- django - 使用AND条件Django过滤具有多个值的同一列
- javascript - Webpack 找不到模块“jquery-form-styler”
- vba - 从上个月的已发送文件夹中检索 Outlook 电子邮件计数(通过 word VBA)
- c# - 返回类型必须是 'bool' 错误
- jquery - jquery - 表单的序列化数组
- php - 如何从 24 小时制 (HHMM) 中减去分钟?