3 回答

TA貢獻(xiàn)1802條經(jīng)驗 獲得超6個贊
使用Array.prototype.reduce,您可以將它們轉(zhuǎn)換為對象,如下所示。
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貢獻(xiàn)1942條經(jīng)驗 獲得超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貢獻(xiàn)1804條經(jīng)驗 獲得超7個贊
2個解決方案:
第一個是聲明一個空對象并使用循環(huán)遍歷每個父對象。
第二種是使用減速機(jī)
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 );
添加回答
舉報