Reputation: 8168
There is a function
that returns key
of an object
based on some condition, if the key
it is returning is 0
, then the value I get is undefined
var obj = {'some','values'};
function getObjectKey(){
obj.forEach(function(value, key) {
if(some condition){
return key;
}
});
}
var objectKey = getObjectKey();
console.log(objectKey); //returns `undefined` if the key returned is 0.
How can I get the key if the key is 0?
Upvotes: 1
Views: 810
Reputation: 11607
You need to specify keys in the object.
This is not valid syntax:
{'some','values'};
This would be an array:
[ 'some','values' ];
But you really want an object, so put in the keys:
{ "key0": "some", "key1": "values" };
Upvotes: 0
Reputation: 386868
You need another methode, because Array#forEach
does not have a short circuit for ending the loop.
In this case, use better Array#some
.
function getObjectKey(object, condition){
var k;
Object.keys(object).some(function(key) {
if (condition(object[key])) {
k = key;
return true;
}
});
return k;
}
var object = { zero: 0, one: 1, two: 2, three: 3, four: 4, five: 5 };
console.log(getObjectKey(object, function (v) { return v === 3; }));
With ES6, you could use Array#find
The
find()
method returns a value in the array, if an element in the array satisfies the provided testing function. Otherwiseundefined
is returned.
function getObjectKey(object, condition) {
return Object.keys(object).find(function(key) {
return condition(object[key]);
});
}
var object = { zero: 0, one: 1, two: 2, three: 3, four: 4, five: 5 };
console.log(getObjectKey(object, v => v === 3));
Upvotes: 1
Reputation: 6282
// there was a syntax error with your obj
var obj = {
'some': 'values',
'another': 'anotherValue',
'zero': 0,
'null': null
}
// you should take the object and the key with the function
function getObjectKey(obj, key){
var keys = Object.keys(obj)
var index = keys.indexOf(key)
// if the bitshifted index is truthy return the key else return undefined
return ~index
? obj[keys[index]]
: void 0 // void value - will change the value given to it to undefined
}
console.log(getObjectKey(obj, 'some'))
console.log(getObjectKey(obj, 'another'))
console.log(getObjectKey(obj, 'doesntExist'))
console.log(getObjectKey(obj, 'zero'))
console.log(getObjectKey(obj, 'null'))
Upvotes: 0