Last Updated: February 25, 2016
·
733
· blaiseliu

The best way to turn a json object into array

Many discussions about this problem. Here is what we use without jQuery:

var characters={
    charlie:'Charlie Brown',
    lucy:'Lucy van Pelt',
    linus:'Linus van Pelt'
};

var output=[];
for (var key in characters) {
    if (characters.hasOwnProperty(key)) {
        output.push(characters[key]);
    }
}

Note there is a hasOwnProperty check to filter out other keys in the json object.


If jQuery is available, please see a pro-tip in the comments section provided by cloze.

2 Responses
Add your response

You can do this in a single $.map().

var array = $.map(_elements, function(el) { return [[el.Name, el.Age, el.ID]]; }); </code>

The double brackets keep $.map() from flattening the array.

over 1 year ago ·

Of course we have more tools with jQuery available. This piece of pro-tip realizes the function with JavaScript only.

But thanks for the input.

over 1 year ago ·