[英]Array of objects to object with keys JSON
This is the data recived from an API Call 这是从API调用中获取的数据
[
{
"id": "id1",
"data": "text"
},
{
"id": "id2",
"data": "text"
}
]
How could i get the JSON data to look like this? 我怎样才能使JSON数据看起来像这样?
{
"id1": {
"data": "text"
},
"id2": {
"data": "text"
}
}
You can use array#reduce
您可以使用
array#reduce
var data = [ { "id": "id1", "data": "text" }, { "id": "id2", "data": "text" } ], result = data.reduce((r,{id,data}) => (r[id] = {data}, r), {}); console.log(result);
You could use Object.assign
a and spread syntax ...
b with Array#map
c for the new properties with destructuring assignment d , computed property names e and short hand properties f . 您可以将
Object.assign
a并使用Array#map
c 扩展语法...
b用于具有解构分配 d , 计算属性名称 e和简写属性 f的新属性。
Object.assign(...array.map(({ id, data }) => ({ [id]: { data } })))
aaaaaaaaaaaaa bbbccccccccc dddddddddddd eeee ffff
var array = [{ id: "id1", data: "text" }, { id: "id2", data: "text" }], object = Object.assign(...array.map(({ id, data }) => ({ [id]: { data } }))); console.log(object);
use lodash groupBy
使用lodash
groupBy
var a = [
{
"id": "id1",
"data": "text"
},
{
"id": "id2",
"data": "text"
}
]
_.groupBy(a, 'id')
result 结果
{
"id1": {
"data": "text"
},
"id2": {
"data": "text"
}
}
or you can use this also 或者你也可以使用它
a.reduce((acc, item) => {
acc[item.id] = item;
return acc;
}, {})
Use any of the two, which ever you find simpler. 使用两者中的任何一个,您会发现更简单。
var arr = [ { "id": "id1", "data": "text" }, { "id": "id2", "data": "text" } ]; var obj = {}; arr.forEach(o => { obj[o.id] = { data: o.data } }) console.log(obj);
var arr = [ { "id": "id1", "data": "text" }, { "id": "id2", "data": "text" } ]; var obj = {}; for (const item of arr) { obj[item.id] = { data: item.data } } console.log(obj);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.