【发布时间】:2023-03-19 11:09:01
【问题描述】:
我正在尝试编写一个函数,该函数接受一个对象数组和无限数量的数组,并将它们组合成一个对象。输入将遵循以下模式:
let x = [{ name: 'Tom' }, { name: 'John' }, { name: 'Harry' }];
let y = [[1, 2, 3], 'id'];
let z = [['a', 'b', 'c'], 'value'];
combine(x, y, z);
以y 和z 的第二个元素作为对象键。使用这些参数,函数应该返回以下数组:
[
{
name: 'Tom',
id: 1,
value: 'a'
},
{
name: 'John',
id: 2,
value: 'b'
},
{
name: 'Harry',
id: 3,
value: 'c'
},
]
应该使用当前对象的索引来获取数组中的正确元素。我已经尝试解决这个问题:
function combine(object, ...arrays) {
return object.map((obj, index) => {
let items = arrays.map(arr => ({
[arr[1]]: arr[0][index]
}));
return Object.assign({}, obj, { items });
});
}
这几乎可以完成这项工作,但导致数组项隐藏在嵌套的 items 数组中,我该如何解决这个问题?
【问题讨论】:
-
使用
map检查Demo
标签: javascript arrays object ecmascript-6