3 回答
TA贡献1802条经验 获得超6个赞
使用Array.prototype.reduce,您可以将它们转换为对象,如下所示。
const fathers = [
'Bob',
'John',
'Ken',
'Steve'
];
const children = [
[ 'Mike', 'David', 'Emma' ],
[],
[ 'Harry' ],
[ 'Alice', 'Jennifer' ]
];
const output = fathers.reduce((acc, curV, curI) => ({ ...acc, [curV]: children[curI] }), {});
console.log(output);
TA贡献1942条经验 获得超3个赞
const fathers = ['Bob', 'John', 'Ken', 'Steve'];
const children = [
['Mike', 'David', 'Emma'],
[],
['Harry'],
['Alice', 'Jennifer']
];
const relation = {};
fathers.forEach((item, index) => {
relation[item] = children[index];
});
console.log(relation);
TA贡献1804条经验 获得超7个赞
2个解决方案:
第一个是声明一个空对象并使用循环遍历每个父对象。
第二种是使用减速机
var fathers = [
'Bob',
'John',
'Ken',
'Steve'
];
var children = [
[ 'Mike', 'David', 'Emma' ],
[],
[ 'Harry' ],
[ 'Alice', 'Jennifer' ]
];
// option 1
var relations = {};
fathers.forEach((father, idx) => relations[father] = children[idx])
console.log(relations);
// option 2
var relations2 = fathers.reduce((acc, father, idx) => {
acc[father] = children[idx];
return acc;
}, {}
)
console.log(relations2 );
添加回答
举报