【问题标题】:Converting an array of arrays into an object with key and value with javascript [duplicate]使用javascript将数组数组转换为具有键和值的对象[重复]
【发布时间】:2021-12-03 21:01:30
【问题描述】:

方法输入:(['name', 'marcus'], ['address', 'New York']

方法输出:{name: marcus, address: New York}

我该怎么做?

cont array = [['c','2'],['d','4']];

function objectify()
{
    array.forEach(arrayElement => { for(let i = 0; i<2; i++){
            const obj = Object.assign({array[i][i]}, array[i++])
    }
    return obj;
})

}

console.log(objectify);

【问题讨论】:

  • 你尝试了什么?
  • 您应该添加minimal reproducible code,以便人们了解您的问题并帮助您。 see why you shouldn't post image as a code or an error
  • 我尝试过使用 foreach,但失败了
  • @MarcusRibas 如果它失败了,不是问题,只是分享你到目前为止所尝试的。即使代码不起作用
  • 我已经编辑了帖子,所以你可以看到我尝试了什么

标签: javascript arrays


【解决方案1】:

您可以使用Object.fromEntries()

const data = [['name', 'marcus'], ['address', 'New York']];
const result = Object.fromEntries(data);
console.log(result);

【讨论】:

    【解决方案2】:

    1) 如果您使用的是forEach,那么您不必在其中使用for 循环

    array.forEach(arrayElement => { for(let i = 0; i<2; i++){
                const obj = Object.assign({array[i][i]}, array[i++])
        }
    

    2)您不应该硬编码i 将运行的长度,因为它可以是任意长度。

    for(let i = 0; i<2; i++)
    

    如果您使用的是forEach,那么您应该遍历数组并获取keyvalue 并将其设置到结果对象中。

    function objectify(array) {
      const result = {};
      
      array.forEach((o) => {
        const [key, value] = o;
        result[key] = value;
      });
    
      return result;
    }
    
    const array = [
      ["c", "2"],
      ["d", "4"],
    ];
    console.log(objectify(array));

    【讨论】:

    • 非常感谢!
    • @MarcusRibas 没问题,格拉斯我可以帮忙
    猜你喜欢
    • 1970-01-01
    • 2023-03-04
    • 2021-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多