admin管理员组文章数量:1433509
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
本文标签: javascriptFinding fieldvalue in JSON arrayStack Overflow
版权声明:本文标题:javascript - Finding field.value in JSON array - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745611601a2666142.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论