【问题标题】:Convert Array into Object of Keys and Values using javascript/jquery [duplicate]使用javascript / jquery将数组转换为键和值的对象[重复]
【发布时间】:2021-02-04 22:48:36
【问题描述】:

我在将数组转换为键和值的对象时遇到问题。

目前,我有以下嵌套数组:

var array = [[id1, parent1, "name1", "desc1"], [id2, parent1, "name2", "desc2"], [id3, parent1, "name3", "desc3"]];

数组的长度是动态的。

对于我的代码,我需要转换数组,使其成为键和值的对象(由每个嵌套数组的第一个 (id) 和第三个 (name) 值组成)。

例如,上述数组的对象如下:

var obj = {id1: name1, id2: name2, id3: name3};

其中 id 值(id1、id2、id3)将是相应的整数值。

如果之前有人问过类似的问题,我深表歉意,但我似乎无法找到一个对我有用的类似问题。

任何帮助或建议将不胜感激!

【问题讨论】:

  • 尽管您已经收到了答案,但 StackOverflow 并不是免费的编码服务。你应该try to solve the problem first。请更新您的问题以在minimal reproducible example 中显示您已经尝试过的内容。如需更多信息,请参阅How to Ask,并拨打tour :)
  • @Barmar 道歉,我无意打扰任何人。将来,我会更清楚我已经尝试过的内容,并且我会参考您引起我注意的“如何提问”主题。

标签: javascript jquery arrays object javascript-objects


【解决方案1】:

你可以用一个简单的for循环来做

var array = [
  ["id1", "parent1", "name1", "desc1"],
  ["id2", "parent1", "name2", "desc2"],
  ["id3", "parent1", "name3", "desc3"]
];

const obj = {}
for (const item of array) {
  obj[item[0]] = item[2];
}

console.log(obj);

【讨论】:

  • 这解决了我的问题,非常感谢!
【解决方案2】:

使用Array.map从数组中的每个元素中提取第一个和第三个条目后,您可以使用Object.fromEntries将提取的​​键/值对数组转换为一个对象:

const [id1, id2, id3, parent1] = [1, 2, 3, 4];

const array = [
  [id1, parent1, "name1", "desc1"],
  [id2, parent1, "name2", "desc2"],
  [id3, parent1, "name3", "desc3"]
];

const obj = Object.fromEntries(array.map(a => [a[0], a[2]]));
console.log(obj);

【讨论】:

    【解决方案3】:

    您基本上希望将原始数组转换为 [key, value] 对的数组。然后,您可以使用 Object.fromEntries 函数将这些键/值转换为对象。所以,是这样的:

    const arr = [
      ["id1", "parent1", "name1", "desc1"],
      ["id2", "parent2", "name2", "desc2"],
      ["id3", "parent3", "name3", "desc3"],
    ];
    
    const results = Object.fromEntries(arr.map(x => ([x[0], x[2]])))
    
    console.log(results)

    【讨论】:

      【解决方案4】:

      作为一种好的做法,建议使用letconst 而不是var,因为var“污染”了全局命名空间,所以这就是我的示例将使用的。
      但是,如果您需要使用var,您可以在我的示例中将const 替换为var,它仍然可以。

      给定以下源数组:

      const array = [
        [id1, parent1, "name1", "desc1"],
        [id2, parent1, "name2", "desc2"],
        [id3, parent1, "name3", "desc3"]
      ];
      

      以下代码块创建一个名为obj 的对象,使用子数组的第一个元素作为键,第三个元素作为值:

      // Create an empty object
      const obj = {};
      
      // Iterate through the source array
      array.forEach((element) => {
        // Assign the 1st element of the sub-array as the property key
        // and the 3rd element as the property value
        obj[element[0]] = element[2];
      });
      
      console.log(obj);
      

      这具有相同的效果,但更简单且占用空间更小:

      const obj = Object.fromEntries(array.map(([key, _, value]) => [key, value]));
      
      console.log(obj);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-23
        相关资源
        最近更新 更多