0

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 ??

4 Answers 4

2

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')
});
Sign up to request clarification or add additional context in comments.

Comments

0

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();
}

Comments

0
var stExist=$.inArray(reqelement, dataArray)

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.