Javascript 如何通过javascript数组中的键和值查找对象的索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11258077/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to find index of an object by key and value in an javascript array
提问by return1.at
Given:
鉴于:
var peoples = [
{ "attr1": "bob", "attr2": "pizza" },
{ "attr1": "john", "attr2": "sushi" },
{ "attr1": "larry", "attr2": "hummus" }
];
Wanted:
通缉:
Index of object where attr === value
for example attr1 === "john"
or attr2 === "hummus"
对象的索引,attr === value
例如attr1 === "john"
或attr2 === "hummus"
Update:Please, read my question carefully, i do not want to find the object via $.inArray nor i want to get the value of a specific object attribute. Please consider this for your answers. Thanks!
更新:请仔细阅读我的问题,我不想通过 $.inArray 找到对象,也不想获取特定对象属性的值。请考虑这一点作为您的答案。谢谢!
回答by jcuenod
The Functional Approach
功能方法
All the cool kids are doing functional programming (hello React users) these days so I thought I would give the functional solution. In my view it's actually a lot nicer than the imperatival for
and each
loops that have been proposed thus far and with ES6 syntax it is quite elegant.
这些天所有的酷孩子都在做函数式编程(你好 React 用户),所以我想我会给出函数式解决方案。在我看来,它实际上比迄今为止提出的 imperativalfor
和each
循环要好得多,而且使用 ES6 语法,它非常优雅。
Update
更新
There's now a great way of doing this called findIndex
which takes a function that return true
/false
based on whether the array element matches (as always, check for browser compatibility though).
现在有一种很好的方法来调用findIndex
它,它接受一个函数,该函数根据数组元素是否匹配返回true
/ false
(一如既往,检查浏览器兼容性)。
var index = peoples.findIndex(function(person) {
return person.attr1 == "john"
}
With ES6 syntax you get to write this:
使用 ES6 语法,你可以这样写:
var index = peoples.findIndex(p => p.attr1 == "john")
The (Old) Functional Approach
(旧)功能方法
TL;DR
TL; 博士
If you're looking for index
where peoples[index].attr1 == "john"
use:
如果您正在寻找index
地方peoples[index].attr1 == "john"
使用:
var index = peoples.map(function(o) { return o.attr1; }).indexOf("john");
Explanation
解释
Step 1
第1步
Use .map()
to get an array of values given a particular key:
使用.map()
得到赋予了特定键值的数组:
var values = object_array.map(function(o) { return o.your_key; });
The line above takes you from here:
上面的行带您从这里开始:
var peoples = [
{ "attr1": "bob", "attr2": "pizza" },
{ "attr1": "john", "attr2": "sushi" },
{ "attr1": "larry", "attr2": "hummus" }
];
To here:
到这里:
var values = [ "bob", "john", "larry" ];
Step 2
第2步
Now we just use .indexOf()
to find the index of the key we want (which is, of course, also the index of the object we're looking for):
现在我们只是.indexOf()
用来查找我们想要的键的索引(当然,这也是我们正在寻找的对象的索引):
var index = values.indexOf(your_value);
Solution
解决方案
We combine all of the above:
我们结合了以上所有内容:
var index = peoples.map(function(o) { return o.attr1; }).indexOf("john");
Or, if you prefer ES6 syntax:
或者,如果您更喜欢 ES6 语法:
var index = peoples.map((o) => o.attr1).indexOf("john");
Demo:
演示:
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);
回答by return1.at
If you want to check on the object itself without interfering with the prototype, use hasOwnProperty()
:
如果您想在不干扰原型的情况下检查对象本身,请使用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;
}
to also include prototype attributes, use:
还包括原型属性,使用:
var getIndexIfObjWithAttr = function(array, attr, value) {
for(var i = 0; i < array.length; i++) {
if(array[i][attr] === value) {
return i;
}
}
return -1;
}
回答by thecodeparadox
Using jQuery .each()
使用 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>
Using for-loop:
使用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]);
}
}
回答by Alain BECKER
Not a direct answer to your question, though I thing it's worth mentioning it, because your question seems like fitting in the general case of "getting things by name in a key-value storage".
不是您问题的直接答案,尽管我认为值得一提,因为您的问题似乎适合“在键值存储中按名称获取事物”的一般情况。
If you are not tight to the way "peoples" is implemented, a more JavaScript-ish way of getting the right guy might be :
如果您对“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;
Hope if this is not the answer you wanted, it might help people interested in that "key/value" question.
希望如果这不是您想要的答案,它可能会帮助对“键/值”问题感兴趣的人。
回答by davids
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;
}
回答by Siva Charan
Do this way:-
这样做:-
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);
});
});
OUTPUT:
输出:
name : john
Refer LIVE DEMO
参考现场演示
?
回答by Tycho
You can also make it a reusable method by expending JavaScript:
您还可以通过扩展 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)