marked-down
marked-down

Reputation: 10408

Return an array of a single property from an array of objects in Javascript

I'm looking for an way to return an array of only a single property of an array of objects in Javascript. Specifically, if I have an array structure formatted to the following specification:

[
    { prop1: "someVar", prop2: "anotherVar" }, 
    { prop1: "foo", prop2: "bar" }, 
    { prop1: "abc", prop2: "def" }
]

How can I return an array of just the prop1 properties? Like following:

[ "someVar", "foo", "abc" ]

I thought I could simply use the .filter method on my original array, like so:

self.myArray.filter(function (el) {
        return el.prop1;
    });

But that clearly doesn't work... Ideas?

Upvotes: 0

Views: 136

Answers (1)

Renato Gama
Renato Gama

Reputation: 16519

Try this;

var newArray = [
    { prop1: "someVar", prop2: "anotherVar" }, 
    { prop1: "foo", prop2: "bar" }, 
    { prop1: "abc", prop2: "def" }
].map(function(item) {
    return item.prop1;
});

In case prop1 is dynamic then you can have a function like;

function extractProperty(array, prop) { //you may want to give it a better name
    return array.map(function(item) {
        return item[prop]; 
    });
}

You can use it like;

var array = extractProperty([
    { prop1: "someVar", prop2: "anotherVar" }, 
    { prop1: "foo", prop2: "bar" }, 
    { prop1: "abc", prop2: "def" }
], 'prop1');

Upvotes: 7

Related Questions