如何在javascript数组中按键和值查找对象的索引
How to find index of an object by key and value in an javascript array
给定:
var peoples = [
{ "attr1": "bob", "attr2": "pizza" },
{ "attr1": "john", "attr2": "sushi" },
{ "attr1": "larry", "attr2": "hummus" }
];
想:
例如attr === value
attr1 === "john"
或attr2 === "hummus"
的对象索引
更新:请仔细阅读我的问题,我不想通过 $.inArray 找到对象,也不想获取特定对象属性的值。请在您的答案中考虑这一点。谢谢!
函数式方法
这些天所有很酷的孩子都在做函数式编程(你好 React 用户),所以我想我会给出函数式解决方案。在我看来,它实际上比迄今为止提出的 imperatival 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");
<小时 />(旧的)功能方法
博士
如果您正在寻找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'
- 如何使用javascript在JSON中动态获取键和值
- 通过angularjs迭代多个字典中的键和值
- JavaScript JSON关联对象键和值都作为日期时间戳
- 使用下划线将键和值的两个数组合并到一个对象中
- jQuery动态更新数据键和值
- 我想重新排列我的数组和其他数组一样,这个数组是键和值
- 在javascript中解析json对象以获取键和值
- 如何为json键和值提供工具提示消息
- 使用JSON键和值动态创建一个表
- 将对象完全转换为键和值的数组:更好的解决方案
- 确定html属性键和值的角度指令
- Javascript移除已知值的键和值数组
- 如何循环json数组以获取javascript中的键和值
- 如何将用户定义的键和值添加到数组中
- 显示关联阵列中所有元素的键和值
- 如何从 javascript 对象中删除键和值
- JavaScript:如何打印数组中的所有键和值
- 在 Javascript 中搜索多个键和值
- 包含键和值数组的字典
- 在对象数组中查找重复的值,并合并一些重复的键和值