-
呼啦一阵风
使用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);
-
手掌心
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);
-
三国纷争
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 );