功能方法
这些天,所有很酷的孩子都在做函数式编程(你好,React用户),所以我想我会给出函数式解决方案。在我看来,它实际上比迄今为止提出的命令for和each循环要好得多,并且使用ES6语法,它非常优雅。
更新资料
现在有一种很棒的方法可以调用findIndex此方法,该方法需要一个函数,该函数根据数组元素是否匹配返回true/ false(与往常一样,尽管要检查浏览器的兼容性)。
var index = peoples.findIndex(function(person) {
return person.attr1 == "john"
}
使用ES6语法,您可以这样编写:
var index = peoples.findIndex(p => p.attr1 == "john")
(旧的)功能方法
TL; DR
如果您要在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);