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.

4
  • stackoverflow.com/questions/237104/… Commented Oct 21, 2013 at 14:58
  • This is not JSON. It's an array of plain objects. Also, I'm pretty sure this is a duplicate. Commented Oct 21, 2013 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 Objects requires they be the exact same object; not just similar. Commented Oct 21, 2013 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. Commented Oct 21, 2013 at 15:02

4 Answers 4

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

Comments

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

Comments

1

Simply iterate over the array to get the value.

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

JsFiddle

Comments

1

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

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.