So lets say i have an array like so
[
{name: "a", happyName: "bob" }
, {name: "b", happyName: "cow" }
, {name: "c", happyName: "moo" }
, {name: "d", happyName: "jen" }
]
What is the most efficient manner to flatten it to an array like so:
[ "a","b","c","d"]
(or alternatively to get only the happyName in the values instead - to be precise, i suppose, how would i flatten some given array into an array of some given named json attribute?)
NB this is javascript only, no JQuery etc stuff please.
This is a good use case for map()
:
var names = theArray.map(function(item) {
return item.name;
});
var happyNames = theArray.map(function(item) {
return item.happyName;
});
If you have to do this a lot, it's quite easy to create a helper:
var names = values(theArray, 'name'),
happyNames = values(theArray, 'happyName');
function values(arr, attr) {
return arr.map(function(item) {
return item[attr];
});
}
var arr = [
{name: "a", happyName: "bob" }
, {name: "b", happyName: "cow" }
, {name: "c", happyName: "moo" }
, {name: "d", happyName: "jen" }
]
var names = arr.map(function(e) { return e.name } )
.map()
is a cool method, but keep in mind it's not compatible with legacy IE (<9). If you want something that'll work everywhere, go for this:
var arrayOfObjects = [
{name: "a", happyName: "bob" },
{name: "b", happyName: "cow" },
{name: "c", happyName: "moo" },
{name: "d", happyName: "jen" }
],
array = [],
i = 0,
len = arrayOfObjects.length;
for(;i<len;i++) {
array.push(arrayOfObjects[i].name);
}
// output => [ "a","b","c","d"]
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.