简体   繁体   中英

Selecting javascript objects via their methods with jquery

How would I select:

object.id2 == "name1";

with jQuery (instead of looping through all of the objects and finding the one who's id2 matches "name1" ), so I could write something like:

$("name1");

or maybe:

$(object + " name1");

or possibly:

$(object).attr('id2','name1');

您可以使用Lodash

var namedObjects = _.find(allObjects, { id2: 'name1' });
var myObj = $('[id2="name1"]') 
//myObj will be an array if there is more than one element that matches

As seen here: jQuery Selector API

This might not be the best way to do it, but if you insist on doing it with jquery, this would be the way to do it:

var theArr = [{id2:"name0"},{id2:"name1"}];

var myObj = $(theArr).filter(function(){
    return this.id2 === "name1";
}).get(0);

console.log(myObj); // Object {id2: "name1"} 

http://jsfiddle.net/Tentonaxe/kTxkr/

of course, if you don't have to support IE<9, you can cut jquery out without changing much:

var theArr = [{id2:"name0"},{id2:"name1"}];

var myObj = theArr.filter(function(obj){
    return obj.id2 === "name1";
})[0];

console.log(myObj); // Object {id2: "name1"} 

http://jsfiddle.net/Tentonaxe/kTxkr/1

I'm not sure I completely understand your question, but if you create an object like this:

var foo = {id2 : "name1"};

You can use a jQuery selector like this:

$(foo)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM