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

Convert Object properties into their own objects possible?

本文关键字:对象 自己的 转换 属性      更新时间:2023-09-26

假设我正在提取一些JSON数据:

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

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

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

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

您可以使用map:获取对象键并在对象上循环

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

DEMO

假设:

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"}]