如何在javascript数组中按键和值查找对象的索引

时间:2012-06-29 07:53:52

标签: javascript jquery

假设:

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

通缉:

attr === value例如attr1 === "john"attr2 === "hummus"

的对象索引

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

7 个答案:

答案 0 :(得分:80)

功能方法

这些天所有很酷的孩子都在进行函数式编程( hello React users ),所以我想我会提供功能性解决方案。在我看来,它实际上比迄今为止提出的impratival foreach循环更好,并且使用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的{​​{1}}:

peoples[index].attr1 == "john"

说明

第1步

使用.map()获取给定特定键的值数组:

var index = peoples.map(function(o) { return o.attr1; }).indexOf("john");

上面的一行将您带到这里:

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" }
];

第2步

现在我们只使用.indexOf()来查找我们想要的键的索引(当然,也是我们正在寻找的对象的索引):

var values = [ "bob", "john", "larry" ];

<强>解决方案

我们结合以上所有内容:

var index = values.indexOf(your_value);

或者,如果您更喜欢ES6语法:

var index = peoples.map(function(o) { return o.attr1; }).indexOf("john");

演示:

&#13;
&#13;
var index = peoples.map((o) => o.attr1).indexOf("john");
&#13;
&#13;
&#13;

答案 1 :(得分:19)

如果您想在不干扰原型的情况下检查对象本身,请使用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;
}

答案 2 :(得分:7)

使用jQuery .each()

$.each(peoples, function(index, obj) {
   $.each(obj, function(attr, value) {
      console.log( attr + ' == ' + value );
   });
});

<强> Working sample

使用 for-loop

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

<强> Working sample

答案 3 :(得分:3)

不是你的问题的直接答案,但我更糟糕的是提到它,因为你的问题似乎适合“在键值存储中按名称获取东西”的一般情况。

如果你对“人民”的实施方式并不紧张,那么获得合适人选的更多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;

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

答案 4 :(得分:2)

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;
}

答案 5 :(得分:0)

这样做: -

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

参考 LIVE DEMO

答案 6 :(得分:0)

您还可以通过扩展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)

相关问题