简体   繁体   English

将JSON / JS对象转换为数组

[英]Converting JSON/JS Object to array

I have a JSON response from my API that is structured like so: 我有一个来自我的API的JSON响应,其结构如下:

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

When I reference data I get the array with each record. 当我引用数据时,每条记录都会得到一个数组。 I need the curly braces to be brackets due to a plugin I am using requiring it to be an array. 由于我使用的插件要求将其作为数组,因此我需要将花括号括起来。

Desired output: 所需的输出:

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

How can I convert the above JSON to this? 如何将上面的JSON转换为此呢?

Edit: 编辑:

This turned out to be a problem with a plugin I was using, and I knew how to do this fine all along. 原来这是我使用的插件存在的问题,而且我一直都知道如何做到这一点。 Thought I was going crazy but my code was fine, some plugin was screwing things up. 以为我疯了,但我的代码很好,某些插件搞砸了。

You can do this using Array.prototype.map 您可以使用Array.prototype.map完成此操作

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

Something like this maybe: http://jsfiddle.net/3gcg6Lbz/1/ 可能是这样的: 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