So I have an array myarr[]
of JSON objects in the form: { "a":"", "b":"" }
Are there efficient methods for getting an array of b:
[ myarr[0].b, myarr[1].b, myarr[2].b, ... ]
Or do I have to manually iterate through the myarr
to build the array of b?
Check out the underscore.js library.
I'd suggest checking out the implementation for pluck .
What you'd want to do is effectively: _.pluck(myarr, 'b')
Why not have fun with prototypes and extend Array to obtain a handy and reusable function:
Array.prototype.pluck = function(key) {
var i = this.length,
plucked = [];
while(i --) {
plucked[i] = this[i][key] || ""
}
return plucked;
}
With this one, you can do:
collection.pluck(keyName)
To get back your desired result. Check here for a working demo: http://jsfiddle.net/jYrNN/1/
var b_arr = $.map(myarr, function(val, i) { return val.b; });
or wihtout jQuery
var b_arr = myarr.map(function(val) { return val.b })
.filter(function(n){return n || false});
jQuery does provide api to parse json
$.each(myarr, function(key,value)
{
alert(key);
alert(value);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.