如何转换对象数组的格式

时间:2017-10-09 13:06:17

标签: jquery json

我的变量有来自JSON的数据,如下所示:

 var dictionary = {
     "data": [{ "id": "0", "name": "ABC" }, { "id": "1", "name": "DEF" }],
     "images": [{ "id": "0", "name": "PQR" }, { "id": "1", "name": "xyz" }]
 };

我想使用jquery在json数据上面拆分并将它们存储在三个变量col [0],col [1]中 我想要这个结果:

var names = Object.getOwnPropertyNames(dictionary);
var col = [];
col[0] = [{
  "id": "0",
  "name": "ABC"
}, {
  "id": "1",
  "name": "DEF"
}]
col[1] = [{
  "id": "0",
  "name": "PQR"
}, {
  "id": "1",
  "name": "xyz"
}]

这是我的代码:

for (var i = 0; i < dictionary.length; i++) {
  for (var key in dictionary[i]) {
    if (col.indexOf(key) === -1) {
      col.push(key);
    }
  }
}

1 个答案:

答案 0 :(得分:1)

您可以使用Object.values()

&#13;
&#13;
var dictionary = {
     "data": [{ "id": "0", "name": "ABC" }, { "id": "1", "name": "DEF" }],
     "images": [{ "id": "0", "name": "PQR" }, { "id": "1", "name": "xyz" }]
 };
 
var col = Object.values(dictionary);
console.log(col);
&#13;
&#13;
&#13;