让我们说我拉一些JSON数据:
[{"a": "1", "b": "2", "c": "3"}]
是否可以将上述内容转换为:
[{"a": "1"}, {"b": "2"}, {"c": "3"}]
如何在JS中实现这一目标?提前谢谢。
答案 0 :(得分:2)
假设:
var myObj = [{"a": "1", "b": "2", "c": "3"}];
然后,你可以这样做:
var result = []; // output array
for(key in myObj[0]){ // loop through the object
if(myObj[0].hasOwnProperty(key)){ // if the current key isn't a prototype property
var temp = {}; // create a temp object
temp[key] = myObj[0][key]; // Assign the value to the temp object
result.push(temp); // And add the object to the output array
}
}
console.log(result);
// [{"a": "1"}, {"b": "2"}, {"c": "3"}]
答案 1 :(得分:2)