将JSON数组转换为对象

时间:2015-08-31 21:49:33

标签: javascript arrays json

我有以下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}
]

我需要变成这个:

{
    "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. "}
}

但我无法弄清楚如何。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

您可以遍历元素,并沿途填充新的对象:

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);

答案 1 :(得分:0)

循环数组以创建新值通常使用reduce,这允许将值累积在一个值中,该值可以传递给下一次回调调用。

在这种情况下,我假设你只想要一个传入的每个成员的浅拷贝,并删除了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));

请注意,这会修改原始对象,而复制它们的代码则不会更长。