Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a variable for a property name when using underscore.js findWhere function?

I'm having trouble figuring out how to set a property dynamically in underscore.js while using the _.findWhere function.

Here's the documentation for the function:

findWhere_.findWhere(list, properties) 

Looks through the list and returns the first value that matches all of the key-value pairs listed in properties.

If no match is found, or if list is empty, undefined will be returned.

_.findWhere(publicServicePulitzers, {newsroom: "The New York Times"});
=> {year: 1918, newsroom: "The New York Times",
reason: "For its public service in publishing in full so many official reports,
documents and speeches by European statesmen relating to the progress and
conduct of the war."}

Modeling the example in the docs, I want to set the property to search for dynamically:

 var publicServicePulitzers = [
    {"newsroom":"The New York Times", "year":2013 },
    {"newsroom":"The Los Angeles Times", "year":2012 }
 ];

var myprop = 'newsroom';
_.findWhere(publicServicePulitzers, { myprop : "The New York Times"});

The result is undefined.

I also tried:

_.findWhere(publicServicePulitzers, {eval(myprop): "The New York Times"});

The error message is SyntaxError: missing : after property id

How can I accomplish this?

Thanks for any help.

like image 452
Timothy Barmann Avatar asked Jan 09 '14 00:01

Timothy Barmann


People also ask

What does the underscore property function return?

Return Value: It returns a function that will return the specified property of an object.

How do you use underscore in JavaScript?

Adding Underscore to a Node. Once added, underscore can be referred in any of the Node. js modules using the CommonJS syntax: var _ = require('underscore'); Now we can use the object underscore (_) to operate on objects, arrays and functions.

What is underscore variable in JavaScript?

the Underscore Prefix in JavaScript Variables The underscore _ is simply an acceptable character for variable/function names; it has no additional functionality. Underscore variable is the standard for private variables and methods. There is no true class privacy in JavaScript.


2 Answers

Just figured it out. The second parameter to findWhere is an object. So create the object first and pass that to the function:

var myprop = 'newsroom';
var value = 'The New York Times';
var search_obj = {};
search_obj[myprop] = value;

var result =  _.findWhere(publicServicePulitzers,search_obj);

Works!

like image 126
Timothy Barmann Avatar answered Oct 04 '22 17:10

Timothy Barmann


Don't use findWhere for this, but a more generic find:

_.find(publicServicePulitzers, function(prize) {
    return price[myprop] == "The New York Times";
});

If you really need to use findWhere, have a look at Using a variable for a key in a JavaScript object literal.

like image 40
Bergi Avatar answered Oct 04 '22 18:10

Bergi