[英]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
)
Using loadash 使用loadash
_.invert(input).cost _.invert(input).cost
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.