javascript - 将键/值对数组转换为对象数组
问题描述
我需要能够将数组转换为包含多个对象的新数组。例如,如果我有这个数组:
["name", "Tom", "id", "48688", "name", "Bob", "id", "91282"]
我希望能够将其转换为:
[{
"name": "Tom",
"id": "48688"
}, {
"name": "Bob"
"id": "91282"
}]
解决方案
使用将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);
推荐阅读
- python - kivy:覆盖 __init__ 使子布局显示太小
- kubernetes - 如何在 linkerd 中禁用 mTLS?
- jquery - JQuery Datepicker选择禁用日期
- amazon-cloudformation - 如何根据 AWS Cloud-formation 中的资源名称获取堆栈详细信息
- javascript - JSX 元素类型 'ReactElement
不是 JSX 元素的构造函数。类型“未定义”不可分配给类型“元素 | 空值' - python - pandas.read_csv 的 Nan 问题
- vue.js - 动态帖子输入
- minecraft - 有没有办法让我的世界java版命令块代码变成我的世界基岩版命令块代码?
- github - 如何接受来自机器人的许多 github PR?
- javascript - 选择独特的项目并将它们标记为js