为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

倚天杖 2023-08-24 17:51:48
我有父亲和孩子的名单: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' ]};
查看完整描述

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);


查看完整回答
反对 回复 2023-08-24
?
手掌心

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);


查看完整回答
反对 回复 2023-08-24
?
三国纷争

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 );


查看完整回答
反对 回复 2023-08-24
  • 3 回答
  • 0 关注
  • 115 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信