[英]Parsing JavaScript Array for specific value
I've a JavaScript Array like 我有一个像这样的JavaScript数组
var main = [
{ "title": "Yes", "path": "images/main_buttons/tick_yes.png"},
{ "title": "No", "path": "images/main_buttons/cross_no.png"},
]
I want to get the corresponding path
value for the item which have a particular title
value. 我想获得具有特定
title
值的项目的相应path
值。
Something like 就像是
var temp = "Yes";
var result = (path value where main[0].title == temp);
I want to get the result
value here. 我想在这里获得
result
值。
If temp == "No"
, it should get me the corresponding path
value. 如果
temp == "No"
,它应该给我相应的path
值。
You can use the Array.prototype.filter
method: 您可以使用
Array.prototype.filter
方法:
var result = main.filter(function(o) {
return o.title === temp;
});
var path = result.length ? result[0].path : null;
Please note that older browsers do not the support the .filter()
method. 请注意,较早的浏览器不支持
.filter()
方法。 However, you can use a polyfill . 但是,您可以使用polyfill 。
Here is one way: 这是一种方法:
var myItem = (function(arr, val){
for(var item in arr){
if(!arr.hasOwnProperty(item) && arr[item].title == val){
return arr[item];
}
}
return null;
})(myJSArray, "valueToMatch");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.