将JS对象数组转换为嵌套形式的最有效方法
Most efficient way to transform array of JS objects to nested form?
我想转换:
[
{id: 1, name: 'one', desc: 'one'},
{id: 2, name: 'two', desc: 'two'},
{id: 3, name: 'three', desc: 'three'}
]
至
{
1: {id: 1, name: 'one', desc: 'one'},
2: {id: 2, name: 'two', desc: 'two'},
3: {id: 3, name: 'three', desc: 'three'}
}
做到这一点最有效/最高效的方法是什么?一些选择是:
1)https://github.com/gaearon/normalizr
2) d3.nest()
3) const object = {}; array.forEach(item => { object[item.id] = item });
我喜欢Array.prototype.reduce()
解决方案。看看这个
var arr = [{id: 1, name: 'one', desc: 'one'}, {id: 2, name: 'two', desc: 'two'}, {id: 3, name: 'three', desc: 'three'}],
obj = arr.reduce((p,c) => {p[c.id] = c; return p},{});
document.write("<pre>" + JSON.stringify(obj,null,2) + "</pre>");
您还可以使用一个简单的循环:
var arr = [{id: 1, name: 'one', desc: 'one'}, {id: 2, name: 'two', desc: 'two'}, {id: 3, name: 'three', desc: 'three'}],
obj = {}
for(var item of arr) obj[item.id] = item;
循环通常比ES5数组方法更快,因为它们不必在每次迭代时调用函数。
我想说它是:
const obj = Object.assign( {}, array );
尽管如此,我还没有将它的性能与您的选择进行比较。
试试这个:
ar = [
{id: 1, name: 'one', desc: 'one'},
{id: 2, name: 'two', desc: 'two'},
{id: 3, name: 'three', desc: 'three'}
]
var result = ar.reduce((ac, x) => {return ac[x.id] = x , ac ;}, {})
document.write( JSON.stringify(result) )
但请记住,键是字符串,处理的是对象而不是数组。。。
相关文章:
- 在jQuery中创建向下滑动子菜单的最有效方法
- 使用Underscore.js修改json数组中所选元素的更有效方法
- 选择具有值数组的所有元素的最有效方法
- 将JSON存储和恢复到此Ionic应用程序的最有效方法
- 将javascript数组中的项移动到特定位置的有效方法
- 将JS对象数组转换为嵌套形式的最有效方法
- 隐藏具有特定类$.each、for等的元素的有效方法
- 什么's是调用具有可变参数的函数的有效方法
- 选择具有特定数据的所有 html 标记的最有效方法是什么 - [适当性],无论值如何
- 使用 jQuery 调用 PHP 端点的最有效方法
- 这是解析 Int 的有效方法吗?
- 在JavaScript中搜索数组映射的最有效方法
- 获取字符串中最后一个换行符的最有效方法是什么
- 什么's是在两个(或多个)阵列中找到匹配的细胞序列的最有效方法
- 什么's是在IE8+中添加元素的最有效方法
- 从任何jquery选择器字符串创建元素的最有效方法
- 在日期范围内查找丢失日期的最有效方法是什么
- 对区间[1,10^12]中的整数进行编码/解码的快速有效方法是什么
- 在条件(if)结构的条件语句中是否有定义变量的有效方法
- 在ASP.NET中使用JQuery UI自动完成的有效方法