Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/466.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/89.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在javascript数组中按键和值查找对象的索引_Javascript_Jquery - Fatal编程技术网

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

如何在javascript数组中按键和值查找对象的索引,javascript,jquery,Javascript,Jquery,给定: var peoples = [ { "attr1": "bob", "attr2": "pizza" }, { "attr1": "john", "attr2": "sushi" }, { "attr1": "larry", "attr2": "hummus" } ]; 通缉令: var peoples = [ { "attr1": "bob", "attr2": "pizza" }, { "attr1": "john", "attr2": "sushi" },

给定:

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

var peoples = [
  { "attr1": "bob", "attr2": "pizza" },
  { "attr1": "john", "attr2": "sushi" },
  { "attr1": "larry", "attr2": "hummus" }
];
对象的索引,其中
attr===value
例如
attr1==“john”
attr2==“hummus”

更新:
请仔细阅读我的问题,我不想通过$.inArray查找对象,也不想获取特定对象属性的值。请考虑一下你的答案。谢谢

如果要在不干扰原型的情况下检查对象本身,请使用:

var getIndexIfObjWithOwnAttr=函数(数组、属性、值){
对于(var i=0;i
要还包括原型属性,请使用:

var getIndexIfObjWithAttr = function(array, attr, value) {
    for(var i = 0; i < array.length; i++) {
        if(array[i][attr] === value) {
            return i;
        }
    }
    return -1;
}
var getIndexIfObjWithAttr=函数(数组、属性、值){
对于(var i=0;i
使用jQuery

var=[
{“attr1”:“bob”,“attr2”:“pizza”},
{“attr1”:“john”,“attr2”:“sushi”},
{“attr1”:“larry”,“attr2”:“hummus”}
];
$。每个(人员、功能(索引、obj){
$.each(对象、函数(属性、值){
console.log(attr+'='+值);
});
});
这样做:-

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);
    });
});
输出: 请参阅


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

如果您对“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;
希望如果这不是您想要的答案,它可能会帮助对“关键/价值”问题感兴趣的人。

功能性方法 这些天所有的酷孩子都在做函数式编程(hello React用户),所以我想我会给出函数式解决方案。在我看来,它实际上比迄今为止提出的
每个
循环的命令式
好得多,并且使用ES6语法,它相当优雅

更新 现在有一种很好的方法可以实现这一点,它使用一个函数,该函数根据数组元素是否匹配返回
true
/
false
(一如既往,检查浏览器兼容性)

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

var index = peoples.findIndex(p => p.attr1 == "john");

(旧的)功能性方法 TL;博士 如果您正在查找
索引
其中
人员[index].attr1==“john”
请使用:

var index = peoples.map(function(o) { return o.attr1; }).indexOf("john");
解释 步骤1

用于获取给定特定键的值数组:

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

现在我们只需使用查找我们想要的键的索引(当然,这也是我们要查找的对象的索引):

解决方案

我们结合了上述所有因素:

var index = peoples.map(function(o) { return o.attr1; }).indexOf("john");
或者,如果您更喜欢ES6语法:

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

演示:
var=[
{“attr1”:“bob”,“attr2”:“pizza”},
{“attr1”:“john”,“attr2”:“sushi”},
{“attr1”:“larry”,“attr2”:“hummus”}
];
var index=peoples.map(函数(o){return o.attr1;}).indexOf(“john”);
log(“约翰的索引:”+索引);
var指数=peoples.map((o)=>o.attr1.indexOf(“拉里”);
log(“拉里的索引:”+索引);
var index=peoples.map(函数(o){return o.attr1;}).indexOf(“fred”);
log(“fred”的索引:“+索引);
var index=peoples.map((o)=>o.attr2.indexOf(“比萨饼”);

log(“attr2”中“pizza”的索引:“+index”)您还可以通过扩展JavaScript使其成为可重用的方法:

Array.prototype.findIndexBy=函数(键,值){
返回此.findIndex(项=>项[key]==值)
}
const peoples=[{name:'john'}]
const cats=[{id:1,名称:'kitty'}]
peoples.findIndexBy('name','john'))
cats.findIndexBy('id',1)

yes的可能重复,相同的用例,但我发现我的问题更一般,例如,如果您没有正在搜索的名为“id”的键,则命中率更高。@FelixKling我认为这不是重复,因为它试图获取与对象相反的索引(您所指的问题没有解决我的问题,但这个问题解决了)。+1,但是为什么不直接返回i(而不是$.inArray(array[i],array);)?为什么要使用
i+=1
而不是
i++
?为什么要使用“array[i].hasOwnProperty(attr)”而不是“array[i][attr]”?@AlainSaint Etienne请参阅我建议在“for”循环之后添加“return-1”,以防找不到元素(类似于javascript的'indexOf'或jquery的'$.inArray'),这不会影响我的用例,但可能对其他人有帮助。我应该更新我的问题,以获得更通用的属性名称,以明确这一点。澄清一点:“return false”可能看起来不必要。可以不使用,但这是一个很好的优化,因为它打破了'$。each()'loop.Good job!另一方面,调用'.toString()'很奇怪(为什么不比较值?),如果'item'上未定义'attr',或者val为'null',或者我错过了使用'toString()的很好的理由,那么很可能会导致错误“在这里?我不清楚为什么我会这样做,但我似乎记得这是因为当值为一个数字时发生了一些冲突链接被破坏了,绝对不需要jQuery。我很遗憾IE不支持
findIndex
函数。现在让我们假设您想知道行
{“attr1”:“bob”,“attr2”中比萨饼的索引:“pizza”}
,也就是“1”,你会怎么做?或者,给定值
“pizza”
,你想知道哪个是对应的
属性名(即:attr2),假设我们在第0行,你会怎么做?可能它会被更新。
findIndex
现在返回-1或找到索引p
var index = values.indexOf(your_value);
var index = peoples.map(function(o) { return o.attr1; }).indexOf("john");
var index = peoples.map((o) => o.attr1).indexOf("john");