将两个数组转换为一个对象

我有父亲和孩子的名单:


const fathers = [

    'Bob',

    'John',

    'Ken',

    'Steve'

];


const children = [

    [ 'Mike', 'David', 'Emma' ],

    [],

    [ 'Harry' ],

    [ 'Alice', 'Jennifer' ]

];

我怎样才能将它们转换为这样的对象:


const relation = {

    Bob: [ 'Mike', 'David', 'Emma' ],

    John: [],

    Ken: [ 'Harry' ],

    Steve: [ 'Alice', 'Jennifer' ]

};


倚天杖
浏览 119回答 3
3回答

呼啦一阵风

使用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 );
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript