I have a javascript object. My console.log
outputs this:
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
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.
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
)
Figured I'd toss an answer in here since Object.Keys() isn't supported before IE9 from what I read.
$.each(yourObject, function(key,value){
if(value === 'cost'){
console.log(key) // key is 2
}
});
Here's a JSFiddle .
Using loadash
_.invert(input).cost
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.