In A Javascript Object, What's Best Way To Get The Attribute Of A Value?
Solution 1:
Caution! There is no guarantee that all browsers return the same result. In fact they don't.
For example:
var x = { a: 1, b: 1 };
delete x.a;
x.a = 1;
What should x.indexOf(1)
return here? b
or a
? Turns out IE does property enumeration differently than other browsers, and the specs say that's perfectly fine. So IE would return a
while other browsers would return b
.
You can verify that by calling
Object.getOwnPropertyNames(x); // IE: a,b - other browsers: b,aObject.keys(x); // samefor (var i in x) { console.log(i); } // same
Obviously, the problem here is that there's no notion of "order" on object indices because, well, that's what objects are: unordered maps.
Solution 2:
Linear search using for..in
construct:
var fruit = null;
for (var prop in calories) {
if (calories[prop] == 280) {
fruit = prop;
break;
}
}
Solution 3:
but there should be a better way
No, there really shouldn't. The way 99% of all use cases go, developers are more interested in getting the value from the key.
Solution 4:
You could extend the prototype of Object doing this:
// Returns one key (any) of the value if it exists, or undefined if notObject.defineProperty(Object.prototype, "keyOf", {
value: function(value) {
for (var key inthis) if (this[key] == value) return key;
returnundefined;
}
});
Using this way instead of the common Object.prototype.keyOf = ...
will work with jQuery if you use it.
And then you could use it like this:
var myArray = {...};
var index = myArray.keyOf(value);
It will also work with normal arrays: [...]
, so you could use it instead of indexOf
too.
Remember to use the triple-character operators to check if it's undefined:
index === undefined// to check the value/index exists
index !== undefined// to check the value/index does not exist
Of course you could change the name of the function if you prefer and remember not to declare any variable called 'undefined'.
Remember also that as indexOf, it will return at most one key defined but it could be more than one possible, so in that case you will need something like this (.keysOf(...)
):
// Returns all the keys of the value if it exists (an empty array if not)Object.defineProperty(Object.prototype, "keysOf", {
value: function(value) {
var allKeys = [];
for (var key inthis) if (this[key] == value) allKeys.push(key);
return allKeys;
}
});
Post a Comment for "In A Javascript Object, What's Best Way To Get The Attribute Of A Value?"