I have a JSON response from my API that is structured like so:
{
"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?
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.
2 Answers 2
You can do this using Array.prototype.map
var arr = json.data.map(function(x){
return [x.id, x.name];
});
answered Oct 13, 2014 at 17:25
Amit Joki
59.4k7 gold badges80 silver badges97 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Felix Kling
@NoahMatisoff: Given the input from your question, it produces exactly the output you wanted: jsfiddle.net/g9frwert . Assuming you parsed the JSON of course.
Something like this maybe: 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);
answered Oct 13, 2014 at 17:27
user1572796
1,0672 gold badges21 silver badges48 bronze badges
5 Comments
Felix Kling
You should avoid using
for...in loops to iterate over arrays.user1572796
I run and get this in the console... [["1", "test"], ["2", "test2"]]
user1572796
@FelixKling how do you typically iterate over arrays?
Felix Kling
With a
for loop: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… user1572796
Why do you choose for loop over for in? It is for performance reasons? I have heard for in is faster. Just curious
lang-js
JSON.stringify()encodes an array or object as JSON. It doesn't change the structure of the array or object.JSON.stringifyto do? You have an array already, so just iterate through it and push theidandnameinto a new array of arrays.