94

鉴于:

var peoples = [
  { "attr1": "bob", "attr2": "pizza" },
  { "attr1": "john", "attr2": "sushi" },
  { "attr1": "larry", "attr2": "hummus" }
];

通缉:

对象的索引,attr === value例如attr1 === "john"attr2 === "hummus"

更新: 请仔细阅读我的问题,我不想通过 $.inArray 找到对象,也不想获取特定对象属性的值。请考虑这一点作为您的答案。谢谢!

4

7 回答 7

186

函数式方法

这些天所有很酷的孩子都在做函数式编程(你好 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);

于 2016-10-01T18:45:26.917 回答
21

如果您想在不干扰原型的情况下检查对象本身,请使用hasOwnProperty()

var getIndexIfObjWithOwnAttr = function(array, attr, value) {
    for(var i = 0; i < array.length; i++) {
        if(array[i].hasOwnProperty(attr) && array[i][attr] === value) {
            return i;
        }
    }
    return -1;
}

还包括原型属性,使用:

var getIndexIfObjWithAttr = function(array, attr, value) {
    for(var i = 0; i < array.length; i++) {
        if(array[i][attr] === value) {
            return i;
        }
    }
    return -1;
}
于 2012-06-29T07:53:53.150 回答
9

使用 jQuery .each()

var peoples = [
  { "attr1": "bob", "attr2": "pizza" },
  { "attr1": "john", "attr2": "sushi" },
  { "attr1": "larry", "attr2": "hummus" }
];

$.each(peoples, function(index, obj) {
   $.each(obj, function(attr, value) {
      console.log( attr + ' == ' + value );
   });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

使用for 循环

var peoples = [
  { "attr1": "bob", "attr2": "pizza" },
  { "attr1": "john", "attr2": "sushi" },
  { "attr1": "larry", "attr2": "hummus" }
];

for (var i = 0; i < peoples.length; i++) {
  for (var key in peoples[i]) {
    console.log(key + ' == ' + peoples[i][key]);
  }
}

于 2012-06-29T07:59:30.257 回答
5

不是对您的问题的直接回答,尽管我认为值得一提,因为您的问题似乎适合“在键值存储中按名称获取事物”的一般情况。

如果您对“peoples”的实现方式并不严格,那么找到合适人选的更类似于 JavaScript 的方式可能是:

var peoples = {
  "bob":  { "dinner": "pizza" },
  "john": { "dinner": "sushi" },
  "larry" { "dinner": "hummus" }
};

// If people is implemented this way, then
// you can get values from their name, like :
var theGuy = peoples["john"];

// You can event get directly to the values
var thatGuysPrefferedDinner = peoples["john"].dinner;

希望如果这不是您想要的答案,它可能会帮助对“键/值”问题感兴趣的人。

于 2012-06-29T08:07:21.283 回答
4
function getIndexByAttribute(list, attr, val){
    var result = null;
    $.each(list, function(index, item){
        if(item[attr].toString() == val.toString()){
           result = index;
           return false;     // breaks the $.each() loop
        }
    });
    return result;
}
于 2012-06-29T07:58:12.663 回答
2

您还可以通过扩展 JavaScript 使其成为可重用的方法:

Array.prototype.findIndexBy = function(key, value) {
    return this.findIndex(item => item[key] === value)
}

const peoples = [{name: 'john'}]
const cats = [{id: 1, name: 'kitty'}]

peoples.findIndexBy('name', 'john')
cats.findIndexBy('id', 1)

于 2019-06-18T08:46:16.740 回答
1

这样做: -

var peoples = [
  { "name": "bob", "dinner": "pizza" },
  { "name": "john", "dinner": "sushi" },
  { "name": "larry", "dinner": "hummus" }
];

$.each(peoples, function(i, val) {
    $.each(val, function(key, name) {
        if (name === "john")
            alert(key + " : " + name);
    });
});

输出:

name : john

参考现场演示

于 2012-06-29T08:04:30.990 回答