0

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?

1 Answer 1

7

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

6 Comments

Gotta think op wants "prop1" (e.g. which property) to be dynamic
Yep - exactly. I deleted my answer that was the same, nice answer. +1
The formal computer-sciencey data-sciency name for it would be project, in case anyone cares.
@renatoargh, thanks for the solution. Yep, the property in question is not dynamic but it's nice to know what would be needed in case it was dynamic. Cheers.
Also, when you ever get into cool libraries, like underscore.js, you can just use pluck which is already in the library for you.
|

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.