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

How to find index of an object by key and value in an javascript array

本文关键字:查找 键和值 对象 索引 javascript 数组      更新时间:2023-09-26

给定:

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

想:

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

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

函数式方法

这些天所有很酷的孩子都在做函数式编程(你好 React 用户),所以我想我会给出函数式解决方案。在我看来,它实际上比迄今为止提出的 imperatival foreach 循环要好得多,并且使用 ES6 语法它非常优雅。

更新

现在有一种很好的方法可以做到这一点,称为findIndex,它采用一个函数,根据数组元素是否匹配返回true/false(与往常一样,检查浏览器兼容性)。

var index = peoples.findIndex(function(person) {
  return person.attr1 == "john"
});

使用 ES6 语法,您可以编写以下内容:

var index = peoples.findIndex(p => p.attr1 == "john");
<小时 />

(旧的)功能方法

博士

如果您正在寻找peoples[index].attr1 == "john"使用的index

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

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

使用 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]);
  }
}

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

如果你不严格理解"people"的实现方式,那么找到合适的人的更像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;

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

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

你也可以通过扩展 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)
这样做

:-

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

参考现场演示

您可以使用

lodash findKey https://docs-lodash.com/v4/find-key/这适用于对象和数组。

例:

import _findKey from 'lodash.findkey';
    var users = {
      'barney':  { 'age': 36, 'active': true },
      'fred':    { 'age': 40, 'active': false },
      'pebbles': { 'age': 1,  'active': true }
    };
     
    _findKey(users, () => o.age < 40);
    // => 'barney' (iteration order is not guaranteed)
     
    // The `_.matches` iteratee shorthand.
    _findKey(users, { 'age': 1, 'active': true });
    // => 'pebbles'
     
    // The `_.matchesProperty` iteratee shorthand.
    _findKey(users, ['active', false]);
    // => 'fred'
     
    // The `_.property` iteratee shorthand.
    _findKey(users, 'active');
    // => 'barney'