简体   繁体   English

在javascript对象中查找元素的位置

[英]Find the position of an element in a javascript object

I have a javascript object. 我有一个JavaScript对象。 My console.log outputs this: 我的console.log输出如下:

Object {1: "name", 2: "cost", 3: "country", 4: "date"}

How do I find the number that corresponds to "cost"? 如何找到与“费用”相对应的数字? I'd like a function that outputs 2 我想要一个输出2的函数

Just iterate over the properties checking their respective values. 只需遍历属性即可检查它们各自的值。

for (var property in object) {
  if (object[property] === 'cost') {
     /// congratulations, you've found it
  }
}

There are of course numerous fancy ways you can do this, eg Object.keys - but they are all fundamentally the same thing. 当然,您可以通过多种奇特的方式来执行此操作,例如Object.keys但它们基本上都是同一件事。

A non-loopy way of doing it would be: 一种非循环的方法是:

 var yourObject = {1: "name", 2: "cost", 3: "country", 4: "date"}; var result = Object.keys(yourObject).find(key => yourObject[key] === 'cost'); console.log(result) // 2 

Assumes you can use ES6 (arrow functions, find ) 假设您可以使用ES6(箭头功能, find

Figured I'd toss an answer in here since Object.Keys() isn't supported before IE9 from what I read. 想通了,我想在这里扔一个答案,因为从我阅读的内容来看,在IE9之前不支持Object.Keys()。

$.each(yourObject, function(key,value){
    if(value === 'cost'){
        console.log(key) // key is 2
    }
});

Here's a JSFiddle . 这是一个JSFiddle

Using loadash 使用loadash

_.invert(input).cost _.invert(input).cost

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM