Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

best way to get the key of a key/value javascript object

People also ask

How do I find a specific key in an object?

You can use the JavaScript in operator to check if a specified property/key exists in an object. It has a straightforward syntax and returns true if the specified property/key exists in the specified object or its prototype chain. Note: The value before the in keyword should be of type string or symbol .

How do you get the keys of an object in an array in JavaScript?

For getting all of the keys of an Object you can use Object. keys() . Object. keys() takes an object as an argument and returns an array of all the keys.

How do you get a key in a value pair?

In order to get a key-value pair from a KiiObject, call the get() method of the KiiObject class. Specify the key for the value to get as the argument of the get() method.


You would iterate inside the object with a for loop:

for(var i in foo){
  alert(i); // alerts key
  alert(foo[i]); //alerts key's value
}

Or

Object.keys(foo)
  .forEach(function eachKey(key) { 
    alert(key); // alerts key 
    alert(foo[key]); // alerts value
  });

You can access each key individually without iterating as in:

var obj = { first: 'someVal', second: 'otherVal' };
alert(Object.keys(obj)[0]); // returns first
alert(Object.keys(obj)[1]); // returns second

If you want to get all keys, ECMAScript 5 introduced Object.keys. This is only supported by newer browsers but the MDC documentation provides an alternative implementation (which also uses for...in btw):

if(!Object.keys) Object.keys = function(o){
     if (o !== Object(o))
          throw new TypeError('Object.keys called on non-object');
     var ret=[],p;
     for(p in o) if(Object.prototype.hasOwnProperty.call(o,p)) ret.push(p);
     return ret;
}

Of course if you want both, key and value, then for...in is the only reasonable solution.


Given your Object:

var foo = { 'bar' : 'baz' }

To get bar, use:

Object.keys(foo)[0]

To get baz, use:

foo[Object.keys(foo)[0]]

Assuming a single object