1

I am trying to determine if a key name is present in my array of object. As an example, how would I verify if the key with a name of 'name' equals the argument passed in my function call? Below is code to further clarify.

var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
var test = function(arr, propName){
var result = [];
for(var i = 0; i < arr.length; i++){
    if(arr[i][propName] === propName){
        result.push(arr[i][propName]);
    }
}
return result;
} 
func(stooges, "name"); 
11
  • What do you expect the test(stooges, 'name') to return? Commented Apr 28, 2015 at 23:52
  • 2
    If you only want to test the presence of the property, you can do if (propName in arr[i]) or if (arr[i].hasOwnProperty(propName). Is that what you want? arr[i][propName] === propName compares the value of the property with its name, which would only be true if you had name: "name" (which would be odd). Commented Apr 28, 2015 at 23:52
  • @Malk I expect test(stooges, "name") to return => ["moe", "larry", "curly"] Commented Apr 28, 2015 at 23:57
  • @TitoEsteves that is explicitly not what your question text asks for. Commented Apr 28, 2015 at 23:57
  • underscorejs.org/#pluck Commented Apr 28, 2015 at 23:58

1 Answer 1

0

Using underscore.js:

var names = _.pluck(stooges, 'name');

In fact this is the very example given on their page?!

So, on the basis that you knew this, but want to know how to write something similar:

function pluck(array, prop]) {
    return array.map(function(entry) {
        return entry[prop];
    });
}

or more safely, returning an empty array if the initial array is undefined:

function pluck(array, prop]) {
    return array ? array.map(function(entry) {
        return entry[prop];
    }) : [];
}
Sign up to request clarification or add additional context in comments.

3 Comments

Yes I am trying to write my own version of the underscore pluck function. I feel it is good practicing. Thanks
@TitoEsteves I've included that too. You could, of course, have just read the source code for underscore...
I did not comprehend that. That is far more advanced then the solution I came up with. Still new to programming.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.