简体   繁体   中英

finding whether a value exists in a javascript object with jquery

I am trying to determine whether a object contains a specific value so that I can be sure not append the value I am looking for more than once and prevent recursion.

I have tried lots of methods but can't get any of them to work:

data = [
  {val:'xxx',txt:'yyy'},
  {val:'yyy',txt:'aaa'},
  {val:'bbb',txt:'ccc'}
];

console.log(jQuery.grep(data, function(obj){
    return obj.txt === "ccc";
}));
$.map(data, function(el) { 
    if(el.txt === 'ccc') 
        console.log('found')
});

Can this be done with map() grep() or inArray() or do I really have to loop through the entire array looking for the value ??

data is an array containing multiple objects, so you'll need to specify the index of the array you wish to look in:

data[0].val === 'xxx';
data[1].val === 'yyy';
data[2].txt === 'ccc';

As an update to your function, what's wrong with $.each ? You're looping anyway with map or grep, so you may as well just be honest about it :P You can loop with for as well, but I'm exampling with $.each as it's almost identical to your current code.

$.each(data, function(el) { 
  if(el.txt === 'ccc') 
    console.log('found')
});

You will have to iterate the whole array as it's an array of objects, and comparing objects is done by the references not by the values.

for (var i = 0; i < data.length; i++){
    if (data[i].val == 'something')
        doSomething();
}

If you wish to avoid all this calculations yourself, there is a utility plugin underscore.js , which has lots of helper.

One of the helpers you are looking for http://underscorejs.org/#contains .

var stExist=$.inArray(reqelement, dataArray)

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