[英]turning an array into an object using es6 map
I currently have the following data structure: 我目前有以下数据结构:
const bar = [
{id:1, version:0, name:"test name A"},
{id:2, version:0, name:"test name B"},
{id:3, version:0, name:"test name C"}
];
And I need to turn it into this: 我需要把它变成这个:
const foo = {
1:{id:1, version:0, name:"test name A"},
2:{id:2, version:0, name:"test name B"},
3:{id:3, version:0, name:"test name C"}
};
The piece of code I actually have is this: 我实际拥有的代码是:
for(let i=0;len = bar.length; i< len;i++){
foo[bar[i].id]= bar[i];
}
I've tried doing 我试过了
bar.map((element,index)=>{
const temporal = {[index]:element};
foo = {...foo, temporal};
});
but I'm lost, any suggestions? 但我迷路了,有什么建议吗?
You can use reduce()
with Object.assign()
你可以使用
reduce()
和Object.assign()
const bar = [ {id:1, version:0, name:"test name A"}, {id:2, version:0, name:"test name B"}, {id:3, version:0, name:"test name C"} ]; var result = bar.reduce((r, e) => Object.assign(r, {[e.id]: e}), {}); console.log(result)
You could use Object.assign
with Array#map
and spread syntax ...
您可以将
Object.assign
与Array#map
和spread语法一起使用...
const bar = [{ id: 1, version: 0, name: "test name A" }, { id: 2, version: 0, name: "test name B" }, { id: 3, version: 0, name: "test name C" }], object = Object.assign(...bar.map(o => ({ [o.id]: o }))); console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Array.map
returns an array, if you wanted to return an object, you could use Array.reduce
instead Array.map
返回一个数组,如果你想返回一个对象,你可以使用Array.reduce
const bar = [ {id:1, version:0, name:"test name A"}, {id:2, version:0, name:"test name B"}, {id:3, version:0, name:"test name C"} ]; var foo = bar.reduce( (a,b,i) => (a[i+1] = b, a), {}); console.log(foo);
If you just need to reformat the data for sending it to an API, there's no need to create true clones of the objects with Object.assign
如果您只需要重新格式化数据以将其发送到API,则无需使用
Object.assign
创建对象的真实克隆
Another way could be to use forEach
which iterates over the array, but doesn't return an array as map
does: 另一种方法可能是使用
forEach
迭代数组,但不会像map
那样返回数组:
let foo = {};
bar.forEach((el, idx) => foo[idx+1] = el)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.