函数式方法
这些天所有很酷的孩子都在做函数式编程(你好 React 用户),所以我想我会给出函数式解决方案。在我看来,它实际上比迄今为止提出的命令式for
和循环要好得多,并且使用 ES6 语法它非常优雅。each
更新
现在有一种很好的方法来调用findIndex
它,它接受一个函数,该函数根据数组元素是否匹配返回true
/ false
(一如既往,检查浏览器兼容性)。
var index = peoples.findIndex(function(person) {
return person.attr1 == "john"
});
使用 ES6 语法,你可以这样写:
var index = peoples.findIndex(p => p.attr1 == "john");
(旧)函数式方法
TL;博士
如果您正在寻找使用index
地点peoples[index].attr1 == "john"
:
var index = peoples.map(function(o) { return o.attr1; }).indexOf("john");
解释
第1步
用于.map()
获取给定特定键的值数组:
var values = object_array.map(function(o) { return o.your_key; });
上面的行带您从这里开始:
var peoples = [
{ "attr1": "bob", "attr2": "pizza" },
{ "attr1": "john", "attr2": "sushi" },
{ "attr1": "larry", "attr2": "hummus" }
];
到这里:
var values = [ "bob", "john", "larry" ];
第2步
现在我们只是.indexOf()
用来查找我们想要的键的索引(当然,这也是我们正在寻找的对象的索引):
var index = values.indexOf(your_value);
解决方案
我们结合以上所有内容:
var index = peoples.map(function(o) { return o.attr1; }).indexOf("john");
或者,如果您更喜欢 ES6 语法:
var index = peoples.map((o) => o.attr1).indexOf("john");
演示:
var peoples = [
{ "attr1": "bob", "attr2": "pizza" },
{ "attr1": "john", "attr2": "sushi" },
{ "attr1": "larry", "attr2": "hummus" }
];
var index = peoples.map(function(o) { return o.attr1; }).indexOf("john");
console.log("index of 'john': " + index);
var index = peoples.map((o) => o.attr1).indexOf("larry");
console.log("index of 'larry': " + index);
var index = peoples.map(function(o) { return o.attr1; }).indexOf("fred");
console.log("index of 'fred': " + index);
var index = peoples.map((o) => o.attr2).indexOf("pizza");
console.log("index of 'pizza' in 'attr2': " + index);