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.
Written by Blaise Liu
Related protips
2 Responses
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.
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.
Have a fresh tip? Share with Coderwall community!
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside