可以将Object属性转换为自己的对象吗?

时间:2014-10-08 11:31:22

标签: javascript arrays object

让我们说我拉一些JSON数据:

[{"a": "1", "b": "2", "c": "3"}]

是否可以将上述内容转换为:

[{"a": "1"}, {"b": "2"}, {"c": "3"}]

如何在JS中实现这一目标?提前谢谢。

2 个答案:

答案 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)

您可以使用map抓取对象键并循环遍历对象:

var newArr = Object.keys(arr[0]).map(function (key) {
  var obj = {};
  obj[key] = arr[0][key];
  return obj;
});

DEMO

相关问题