Parsing json responses the lazy (as in I-hate-if's) way
(Yes, I don't know how to name the tip).
Suppose you have an API call that might answer a json/js object in the following formats:
One item:
{
foos: {
bar: 1
}
}
A bunch of items:
{
foos: [{
bar: 1
}, {
bar: 6
}]
}
No item at all:
{
foos: { }
}
BTW: This is actually quite common in API's that just translate XML to JSON.
One way to handle all 3 cases is to simply do:
var array_of_foos = [].concat(obj.foos || []);
This way array_of_foos will always contain either an empty array, or an array with all the items.
Written by Daniel Tralamazza
Related protips
4 Responses
Wouldn't the following do the trick too?
var arrayoffoos = obj.foos || [];
EDIT:
Ah, stupid, the concat takes care of the single value issue of course.
Nope, in the case where obj.foos has only 1 object, you want an array with 1 item. That would be case #1.
@tralamazza Just realised. Nice way of sanitising the data.
@guido thanks :) and may the laziness be with you too
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