0
var x = [{ a: 1, b: 2}, { a: 11, b: 12}, { a: 31, b: 23}, { a: 51, b: 24}]

how do you find a = 11 ?

for simple arrays one can do x.indexOf('1'); so perhaps the solution should be something like

var a1 = x.indexOf({a: 1});

ofcourse, I want to obtain the entire JSON for which the value matches.

Csharp
  • 2,916
  • 16
  • 50
  • 77
Sangram Singh
  • 7,161
  • 15
  • 50
  • 79
  • http://stackoverflow.com/questions/237104/array-containsobj-in-javascript – sunn0 Oct 21 '13 at 14:58
  • This is not JSON. It's an array of plain objects. Also, I'm pretty sure this is a duplicate. – John Dvorak Oct 21 '13 at 14:59
  • 1
    JavaScript doesn't have built-in support for object querying like you're expecting. Though, there may be libraries that can add it. But, `indexOf()` searches with `===`, which for `Object`s requires they be the exact same object; not just similar. – Jonathan Lonowski Oct 21 '13 at 15:01
  • @JonathanLonowski thanks. thats what i wanted to know. I can now look at both recommended solution of writing code or using underscore lib. – Sangram Singh Oct 21 '13 at 15:02

4 Answers4

4

you can do it with a simple function, no third party modules needed:

var x = [{ a: 1, b: 2}, { a: 11, b: 12}, { a: 31, b: 23}, { a: 51, b: 24}];

function getIndexOf(value){
    for(var i=0; i<x.lengh; i++){
        if(x[i].a == value)
            return i;
    }
}

alert(getIndexOf(value)); // output is: 1
Nasser Torabzade
  • 6,490
  • 8
  • 27
  • 36
2

You can use Array.Filter with shim support on older browsers.

var x = [{
    a: 1,
    b: 2
}, {
    a: 11,
    b: 12
}, {
    a: 31,
    b: 23
}, {
    a: 51,
    b: 24
}],
tocomp = 11;
var res = x.filter(function (ob) { 
    return ob.a === tocomp;
});

Result will be array of object that matches the condition.

Fiddle

And if you just care for single match and get back the matched object just use a for loop.

var x = [{
    a: 1,
    b: 2
}, {
    a: 11,
    b: 12
}, {
    a: 31,
    b: 23
}, {
    a: 51,
    b: 24
}],
tocomp = 11, i, match;
for (i=0, l=x.length; i<l; i++){
    if(x[i].a === tocomp){
        match = x[i];
        break; //break after finding the match
    }
}
PSL
  • 123,204
  • 21
  • 253
  • 243
1

Simply iterate over the array to get the value.

for(var i = 0;i < x.length; i++){
   alert(x[i].a);
}

JsFiddle

Sachin
  • 40,216
  • 7
  • 90
  • 102
1

You can use native js or you can use underscoreJS lib. UnderscoreJS