解析JavaScript数组以获取特定值

pta*_*mzz 1 javascript parsing json

我有一个JavaScript数组

var main = [
 { "title": "Yes", "path": "images/main_buttons/tick_yes.png"},
 { "title": "No", "path": "images/main_buttons/cross_no.png"},
]
Run Code Online (Sandbox Code Playgroud)

我想获得path具有特定title值的项目的相应值.

就像是

var temp = "Yes";
var result = (path value where main[0].title == temp);
Run Code Online (Sandbox Code Playgroud)

我想在result这里得到价值.

如果temp == "No",它应该得到相应的path值.

und*_*ned 5

您可以使用以下Array.prototype.filter方法:

var result = main.filter(function(o) {
    return o.title === temp;
});

var path = result.length ? result[0].path : null;
Run Code Online (Sandbox Code Playgroud)

请注意,旧版浏览器不支持该.filter()方法.但是,您可以使用polyfill.