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
Add your response
Add your response
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.
over 1 year ago
·
Nope, in the case where obj.foos has only 1 object, you want an array with 1 item. That would be case #1.
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Api
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#