[英]Converting JSON array to objects
I have the following JSON array:我有以下 JSON 数组:
[
{"id": "01", "state": "Alabama", "category": "Coal", "detail1": null, "detail2": null},
{"id": "02", "state": "Alaska", "category": null, "detail1": null, "detail2": null},
{"id": "04", "state": "Arizona", "category": "Oil", "detail1": null, "detail2": null}
]
That I need to turn into this:我需要变成这样:
{
"01": { "state":"Alabama", "category":"A", "detail1":"Status 1", "detail2":"Lorem ipsum dolor sit amet, consectetur adipiscing elit. "},
"02": { "state":"Alaska", "category":"B", "detail1":"Status2", "detail2":"Integer egestas fermentum neque vitae mattis. "},
"04": { "state":"Arizona", "category":"C", "detail1":"Status 3", "detail2":"Fusce hendrerit ac enim a consequat. "}
}
But I can't figure out how.但我无法弄清楚如何。 Can anyone help?
任何人都可以帮忙吗?
You can loop over the elements, and populate a new Object along the way:您可以遍历元素,并在此过程中填充一个新对象:
var arr = [ {"id": "01", "state": "Alabama", "category": "Coal", "detail1": null, "detail2": null}, {"id": "02", "state": "Alaska", "category": null, "detail1": null, "detail2": null}, {"id": "04", "state": "Arizona", "category": "Oil", "detail1": null, "detail2": null} ]; // Here, I create a copy of the array to avoid modifying the original one. var obj = {}, copy = JSON.parse( JSON.stringify(arr) ); for(var i in copy){ obj[ copy[i].id ] = copy[i]; // Add the element to obj, at index id delete copy[i].id; // Remove the id from the inserted object } console.log(obj);
Looping over an array to create a new value typically uses reduce , which allows values to be accumulated in a value that can be passed along to the next invocation of the callback.循环遍历数组以创建新值通常使用reduce ,它允许将值累积在可以传递给下一次回调调用的值中。
I'll assumed in this case that you just want a shallow copy of each member passed in with the id property removed and added to the new value, which can be an object:在这种情况下,我假设您只需要传入的每个成员的浅拷贝,删除 id 属性并添加到新值中,该值可以是一个对象:
var arr = [ {"id": "01", "state": "Alabama", "category": "Coal", "detail1": null, "detail2": null}, {"id": "02", "state": "Alaska", "category": null, "detail1": null, "detail2": null}, {"id": "04", "state": "Arizona", "category": "Oil", "detail1": null, "detail2": null} ] // Loop over all numeric members of arr var newStructure = arr.reduce(function(obj, v){ // Store the value of the ID property of the passed in object var id = v.id; // Remove the id property from the passed in object delete v.id; // Add the id value and remainder of the object to the accumulator obj[id] = v; // Return the accumulator return obj; },{}); document.write(JSON.stringify(newStructure));
Note that this modifies the original objects, the code to copy them instead isn't much longer.请注意,这会修改原始对象,而不是复制它们的代码不会太长。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.