首页 > 解决方案 > 将键/值对数组转换为对象数组

问题描述

我需要能够将数组转换为包含多个对象的新数组。例如,如果我有这个数组:

["name", "Tom", "id", "48688", "name", "Bob", "id", "91282"]

我希望能够将其转换为:

[{
   "name": "Tom",
   "id": "48688"
}, {
   "name": "Bob"
   "id": "91282"
}]

标签: javascriptarraysobject

解决方案


使用将for其迭代递增 的循环4,如下所示:

let results = [];
for(let i = 0; i < array.length; i += 4) {    // increment i by 4 to get to the start of the next object data
  results.push({
    id: array[i + 3],                         // array[i + 0] is the string "name", array[i + 1] is the name,
    name: array[i + 1]                        // array[i + 2] is the string "id" and array[i + 3] is the id
  });
}

演示:

let array = ["name", "Tom", "id", "48688", "name", "Bob", "id", "91282", "name", "Ibrahim", "id", "7"];

let results = [];
for(let i = 0; i < array.length; i += 4) {
  results.push({
    id: array[i + 3],
    name: array[i + 1]
  });
}

console.log(results);


推荐阅读