简体   繁体   English

获取特定的数组值

[英]Get specific array value

var stored =
        [{subject:"farm",name:"John Doe"},
         {subject:"steam",name:"Michael Buck"},
         {subject:"finance",name:"Ron Ruckle"}, //need this
         {subject:"geo",name:"Ben Bond"}];

I need to get an specific array value. 我需要获取一个特定的数组值。 I know it is possible to do this: 我知道可以这样做:

     getitem = stored[2]["name"];

but since I don't know the row, only the first item's value I need something like this: 但由于我不知道该行,所以只有第一项的值需要以下内容:

     getitem = stored["subject:finance"]["name"];

You'd have to iterate and check: 您必须进行迭代并检查:

function getNameFromSubject(subject) {
    for (var i = 0; i < stored.length; i++) {
        if (stored[i].subject == subject) return stored[i].name;
    }
    return null;
}

var name = getNameFromSubject("finance");

With modern browsers, you can use filter() to find the element you need, then get its name: 在现代浏览器中,您可以使用filter()查找所需的元素,然后获取其名称:

var results = stored.filter(
  function( item )
  {
    return item.subject == "finance";
  }
);

var name = results[0].name;

The MDN docs show how to add a filter() method for older browsers, as well. MDN文档还显示了如何为旧版浏览器添加filter()方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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