1

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.

4 Answers 4

3

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];
    });
}
Sign up to request clarification or add additional context in comments.

Comments

2

You can use Array.map for that

var names = arr.map(function(obj) {
    return obj.name;
});

FIDDLE

Comments

1
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 } )

Comments

1

.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"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.