简体   繁体   English

解析JavaScript数组以获取特定值

[英]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

I'd do it like this 我会这样

function getPath(title, arr) {
    for (var i=arr.length;i--;) {
        if (arr[i].title == title) return arr[i].path;
    }
}

called like 叫像

getPath('Yes', main); // returns the path or undefined

FIDDLE 小提琴

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM