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.
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.
Share Improve this question edited Oct 21, 2013 at 14:59 Csharp 2,98216 gold badges50 silver badges77 bronze badges asked Oct 21, 2013 at 14:55 Sangram SinghSangram Singh 7,19115 gold badges51 silver badges79 bronze badges 4- stackoverflow./questions/237104/… – sunn0 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. – John Dvorak 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 forObject
s requires they be the exact same object; not just similar. – Jonathan Lonowski Commented Oct 21, 2013 at 15:01 - @JonathanLonowski thanks. thats what i wanted to know. I can now look at both remended solution of writing code or using underscore lib. – Sangram Singh Commented Oct 21, 2013 at 15:02
4 Answers
Reset to default 4you 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
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
}],
top = 11;
var res = x.filter(function (ob) {
return ob.a === top;
});
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
}],
top = 11, i, match;
for (i=0, l=x.length; i<l; i++){
if(x[i].a === top){
match = x[i];
break; //break after finding the match
}
}
Simply iterate over the array to get the value.
for(var i = 0;i < x.length; i++){
alert(x[i].a);
}
JsFiddle
You can use native js or you can use underscoreJS lib. UnderscoreJS
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745611602a4635977.html
评论列表(0条)