251

If I have a JS object like:

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

If I know that foo has that basic key/value structure, but don't know the name of the key, How can I get it? for ... in? $.each()?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
sprugman
  • 19,351
  • 35
  • 110
  • 163

20 Answers20

253

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
  });
Michael Benin
  • 4,317
  • 2
  • 23
  • 15
135

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
user01
  • 1,575
  • 1
  • 12
  • 14
  • 4
    You can now use spread operator for this purpose, it looks better: ```const [firstKey, ...rest] = Object.keys(obj);``` – Nerlin Dec 13 '17 at 21:08
98

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.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • `p` gives me the key but how do I get the value of the key? Thanks. – Si8 Nov 22 '17 at 17:24
  • 3
    For both keys and values, use the new Object.entries() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries – Kzqai Jun 07 '19 at 16:35
  • perhaps it's an indication of my limited understanding, but this answer seems incredibly verbose (admittedly reusable) for something as simple as getting a key/value. Shouldn't @Michael Benin answer be marked as the best one? – Aaron Matthews Aug 02 '19 at 09:28
  • 10
    Erm... does anyone else clicking the first link get redirected to narcotics anonymous? – John Duskin Aug 27 '19 at 14:45
88

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

Aryeh Beitz
  • 1,974
  • 1
  • 22
  • 23
40

This is the simplest and easy way. This is how we do this.

var obj = { 'bar' : 'baz' }
var key = Object.keys(obj)[0];
var value = obj[key];
     
 console.log("key = ", key) // bar
 console.log("value = ", value) // baz
Object.keys() is javascript method which return an array of keys when using on objects.
Object.keys(obj) // ['bar']

Now you can iterate on the objects and can access values like below-

Object.keys(obj).forEach( function(key) {
  console.log(obj[key]) // baz
})
Mustkeem K
  • 8,158
  • 2
  • 32
  • 43
36

A one liner for you:

const OBJECT = {
    'key1': 'value1',
    'key2': 'value2',
    'key3': 'value3',
    'key4': 'value4'
};

const value = 'value2';

const key = Object.keys(OBJECT)[Object.values(OBJECT).indexOf(value)];

window.console.log(key); // = key2
theonelucas
  • 584
  • 7
  • 12
28
// iterate through key-value gracefully
const obj = { a: 5, b: 7, c: 9 };
for (const [key, value] of Object.entries(obj)) {
  console.log(`${key} ${value}`); // "a 5", "b 7", "c 9"
}

Refer MDN

aiffin
  • 509
  • 4
  • 11
  • Highly underrated answer. You can also use the functional approach, `Object.entries(object1).forEach(([key, value]) => { console.log(\`${key}: ${value}\`); })` – brandonscript Jan 02 '22 at 23:39
20

I was having the same problem and this is what worked

//example of an Object
var person = {
    firstName:"John",
    lastName:"Doe",
    age:50,
    eyeColor:"blue"
};

//How to access a single key or value
var key = Object.keys(person)[0];
var value = person[key];
pride
  • 85
  • 1
  • 11
Chris
  • 491
  • 5
  • 9
14

best way to get key/value of object.

let obj = {
        'key1': 'value1',
        'key2': 'value2',
        'key3': 'value3',
        'key4': 'value4'
    }
    Object.keys(obj).map(function(k){ 
    console.log("key with value: "+k +" = "+obj[k])    
    
    })
    
Sahil Ralkar
  • 2,331
  • 23
  • 25
9

I don't see anything else than for (var key in foo).

patapizza
  • 2,398
  • 15
  • 14
5

The easiest way is to just use Underscore.js:

keys

_.keys(object) Retrieve all the names of the object's properties.

_.keys({one : 1, two : 2, three : 3}); => ["one", "two", "three"]

Yes, you need an extra library, but it's so easy!

Community
  • 1
  • 1
samnau
  • 683
  • 7
  • 7
  • 4
    @lonesomeday yes, but underscore/lodash are useful in many other ways, so it's worth bringing up. – jcollum Dec 10 '13 at 19:42
5

Since you mentioned $.each(), here's a handy approach that would work in jQuery 1.6+:

var foo = { key1: 'bar', key2: 'baz' };

// keys will be: ['key1', 'key2']
var keys = $.map(foo, function(item, key) {
  return key;
});
Dave Ward
  • 59,815
  • 13
  • 117
  • 134
4

use for each loop for accessing keys in Object or Maps in javascript

for(key in foo){
   console.log(key);//for key name in your case it will be bar
   console.log(foo[key]);// for key value in your case it will be baz
}

Note: you can also use

Object.keys(foo);

it will give you like this output:

[bar];

jitendra varshney
  • 3,484
  • 1
  • 21
  • 31
4

Object.keys() The Object.keys() method returns an array of a given object's own enumerable properties, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

var arr1 = Object.keys(obj);

Object.values() The Object.values() method returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

var arr2 = Object.values(obj);

For more please go here

jesusverma
  • 1,625
  • 1
  • 16
  • 17
3

There is no way other than for ... in. If you don't want to use that (parhaps because it's marginally inefficient to have to test hasOwnProperty on each iteration?) then use a different construct, e.g. an array of kvp's:

[{ key: 'key', value: 'value'}, ...]
Jamie Treworgy
  • 23,934
  • 8
  • 76
  • 119
2

You can use Object.keys functionality to get the keys like:

const tempObjects={foo:"bar"}

Object.keys(tempObjects).forEach(obj=>{
   console.log("Key->"+obj+ "value->"+tempObjects[obj]);
});
Michael Nelles
  • 5,426
  • 8
  • 41
  • 57
2

Well $.each is a library construct, whereas for ... in is native js, which should be better

Naftali
  • 144,921
  • 39
  • 244
  • 303
0

for showing as a string, simply use:

console.log("they are: " + JSON.stringify(foo));
Jiulong Zhao
  • 1,313
  • 1
  • 15
  • 25
0

If you are using AWS CloudFront Functions then this would work for you.

function handler(event) {
    var response = event.response;
    var headers = response.headers;
    if("x-amz-meta-csp-hash" in headers){ 
        hash=headers["x-amz-meta-csp-hash"].value;
        console.log('hash is ' + hash);
    }
}
Raushan
  • 185
  • 1
  • 9
0

Readable and simple solution:

const object1 = {
    first: 'I am first',
    second: 'I am second'
};

for (const [key, value] of Object.entries(object1)) {
    console.log(`${key}: ${value}`);
}

// expected output:
// "first: I am first"
// "second: I am second"
DiZiNnEs
  • 71
  • 1
  • 3