簡體   English   中英

將JSON / JS對象轉換為數組

[英]Converting JSON/JS Object to array

我有一個來自我的API的JSON響應,其結構如下:

{
  "data": [
    {
      "id": "1", "name": "test"
    },
    {
      "id": "2", "name": "test2"
    }
  ]
}

當我引用數據時,每條記錄都會得到一個數組。 由於我使用的插件要求將其作為數組,因此我需要將花括號括起來。

所需的輸出:

[
  ["1", "test"],
  ["2", "test"]
]

如何將上面的JSON轉換為此呢?

編輯:

原來這是我使用的插件存在的問題,而且我一直都知道如何做到這一點。 以為我瘋了,但我的代碼很好,某些插件搞砸了。

您可以使用Array.prototype.map完成此操作

var arr = json.data.map(function(x){ 
   return [x.id, x.name]; 
});

可能是這樣的: http : //jsfiddle.net/3gcg6Lbz/1/

var arr = new Array();
var obj = {
  "data": [
    {
      "id": "1", "name": "test"
    },
    {
      "id": "2", "name": "test2"
    }
  ]
}

for(var i in obj.data) {
  var thisArr = new Array();
  thisArr.push(obj.data[i].id);
  thisArr.push(obj.data[i].name);
  arr.push(thisArr);
}

console.log(arr);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM