Reputation: 2677
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 ??
Upvotes: 0
Views: 2161
Reputation: 15802
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')
});
Upvotes: 2
Reputation: 1968
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.
Upvotes: 0
Reputation: 150253
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();
}
Upvotes: 0