3 回答

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