549

If there is a JavaScript object:

var objects={...};

Suppose, it has more than 50 properties, without knowing the property names (that's without knowing the 'keys') how to get each property value in a loop?

nonopolarity
  • 146,324
  • 131
  • 460
  • 740
Mellon
  • 37,586
  • 78
  • 186
  • 264
  • 27
    Note to readers: dont' miss the very insightful [second answer](http://stackoverflow.com/a/16643074/641451) – Pandaiolo Jan 04 '16 at 17:17
  • Possible duplicate of [How to list the properties of a JavaScript object](http://stackoverflow.com/questions/208016/how-to-list-the-properties-of-a-javascript-object) – Nerdroid Feb 05 '17 at 11:49

25 Answers25

1152

Depending on which browsers you have to support, this can be done in a number of ways. The overwhelming majority of browsers in the wild support ECMAScript 5 (ES5), but be warned that many of the examples below use Object.keys, which is not available in IE < 9. See the compatibility table.

ECMAScript 3+

If you have to support older versions of IE, then this is the option for you:

for (var key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
        var val = obj[key];
        // use val
    }
}

The nested if makes sure that you don't enumerate over properties in the prototype chain of the object (which is the behaviour you almost certainly want). You must use

Object.prototype.hasOwnProperty.call(obj, key) // ok

rather than

obj.hasOwnProperty(key) // bad

because ECMAScript 5+ allows you to create prototypeless objects with Object.create(null), and these objects will not have the hasOwnProperty method. Naughty code might also produce objects which override the hasOwnProperty method.

ECMAScript 5+

You can use these methods in any browser that supports ECMAScript 5 and above. These get values from an object and avoid enumerating over the prototype chain. Where obj is your object:

var keys = Object.keys(obj);

for (var i = 0; i < keys.length; i++) {
    var val = obj[keys[i]];
    // use val
}

If you want something a little more compact or you want to be careful with functions in loops, then Array.prototype.forEach is your friend:

Object.keys(obj).forEach(function (key) {
    var val = obj[key];
    // use val
});

The next method builds an array containing the values of an object. This is convenient for looping over.

var vals = Object.keys(obj).map(function (key) {
    return obj[key];
});

// use vals array

If you want to make those using Object.keys safe against null (as for-in is), then you can do Object.keys(obj || {})....

Object.keys returns enumerable properties. For iterating over simple objects, this is usually sufficient. If you have something with non-enumerable properties that you need to work with, you may use Object.getOwnPropertyNames in place of Object.keys.

ECMAScript 2015+ (A.K.A. ES6)

Arrays are easier to iterate with ECMAScript 2015. You can use this to your advantage when working with values one-by–one in a loop:

for (const key of Object.keys(obj)) {
    const val = obj[key];
    // use val
}

Using ECMAScript 2015 fat-arrow functions, mapping the object to an array of values becomes a one-liner:

const vals = Object.keys(obj).map(key => obj[key]);

// use vals array

ECMAScript 2015 introduces Symbol, instances of which may be used as property names. To get the symbols of an object to enumerate over, use Object.getOwnPropertySymbols (this function is why Symbol can't be used to make private properties). The new Reflect API from ECMAScript 2015 provides Reflect.ownKeys, which returns a list of property names (including non-enumerable ones) and symbols.

Array comprehensions (do not attempt to use)

Array comprehensions were removed from ECMAScript 6 before publication. Prior to their removal, a solution would have looked like:

const vals = [for (key of Object.keys(obj)) obj[key]];

// use vals array

ECMAScript 2017+

ECMAScript 2016 adds features which do not impact this subject. The ECMAScript 2017 specification adds Object.values and Object.entries. Both return arrays (which will be surprising to some given the analogy with Array.entries). Object.values can be used as is or with a for-of loop.

const values = Object.values(obj);

// use values array or:

for (const val of Object.values(obj)) {
    // use val
}

If you want to use both the key and the value, then Object.entries is for you. It produces an array filled with [key, value] pairs. You can use this as is, or (note also the ECMAScript 2015 destructuring assignment) in a for-of loop:

for (const [key, val] of Object.entries(obj)) {
    // use key and val
}

Object.values shim

Finally, as noted in the comments and by teh_senaus in another answer, it may be worth using one of these as a shim. Don't worry, the following does not change the prototype, it just adds a method to Object (which is much less dangerous). Using fat-arrow functions, this can be done in one line too:

Object.values = obj => Object.keys(obj).map(key => obj[key]);

which you can now use like

// ['one', 'two', 'three']
var values = Object.values({ a: 'one', b: 'two', c: 'three' });

If you want to avoid shimming when a native Object.values exists, then you can do:

Object.values = Object.values || (obj => Object.keys(obj).map(key => obj[key]));

Finally...

Be aware of the browsers/versions you need to support. The above are correct where the methods or language features are implemented. For example, support for ECMAScript 2015 was switched off by default in V8 until recently, which powered browsers such as Chrome. Features from ECMAScript 2015 should be be avoided until the browsers you intend to support implement the features that you need. If you use babel to compile your code to ECMAScript 5, then you have access to all the features in this answer.

qubyte
  • 17,558
  • 3
  • 30
  • 32
  • 11
    This should be the accepted (or atleast more upvoted) answer as the accepted one is incomplete (@olive points this out). – 0xc0de Sep 26 '13 at 12:02
  • It's a shame that of all the so-called tricks, we still need to mention `obj` twice. I guess creating a helper function is unavoidable? Something like values(obj). – Steven Haryanto Nov 23 '13 at 09:16
  • Any of these methods can be used as a shim. For example: `Object.values = obj => Object.keys(obj).map(key => obj[key]);` – qubyte Nov 24 '13 at 02:43
  • To the downvoter, please leave a comment. I'll do my best to address criticism, but I can't do anything without knowing what the issue was. – qubyte Nov 24 '13 at 02:45
  • I'm not the one who downvoted you, but perhaps it was because your code generates an " Unexpected token > " syntax error. – Jacek Lampart Dec 01 '13 at 03:46
  • 1
    The ECMA 5 solutions should work in all modern browsers. ECMA 6 has not yet been finalised, and support is preliminary in all browsers. In Chrome, ECMA 6 is partially implemented but disabled. In Firefox, the support is better but the array comprehension are wrong (as mentioned). I thought my use of the future tense would imply this. @JacekLampart, which solution gave you the error? – qubyte Dec 01 '13 at 11:18
  • Thank you for a very comprehensive answer. Also note that there are several ways to compile ES6 to ES5 so you can begin using arrow functions now. TypeScript does this for example. – styfle Dec 11 '14 at 03:01
  • 2
    I can't imagine why we have to wait for ES2017 to get an Object.values() method. – Herbertusz Mar 13 '16 at 22:13
  • *"Finally, as noted in the comments and by teh_senaus in another answer, it may be worth using one of these as a shim. Don't worry, the following does not change the prototype, it just adds a method to Object (which is much less dangerous)."* Even so, isn't it better to check `if (!Object.values)` before overriding the possibly more efficient engine implementation? – doplumi Aug 29 '16 at 11:19
  • It depends. If you prefer consistency, then you might want to always replace the method. I'll update to make it clearer though. Thanks! – qubyte Aug 29 '16 at 11:45
  • Doesn't the `Object.keys(..).map(..)` approach wind up iterating over an object twice? Once to convert the keys to an array and then again during the `.map`? It seems that performance-minded people would actually prefer the `for key in obj | if (hasOwnProperty)` approach, as this iterates a single time. – kevlarr May 30 '17 at 18:06
  • @kevlarr in principle you're right, although my understanding is that none of the major JS engines do it in JS, opting to use underlying access to their implementations of Object to collect keys. A few non-scientific tests show that filtered for-in performs consistently worse than using Object.keys and iterating over the result. Of course, it's always worth checking the perf of both when coding a hot path! – qubyte May 30 '17 at 22:37
  • @qubyte Ah fascinating, I haven't seen any numbers showing this would actually be more efficient. I can imagine there could be some magic under the hood, but given that most JS environments don't have any implementations of iterators/generators/streams, I assumed this would not already have been optimized for the `.keys(..).map(..)` technique – kevlarr May 31 '17 at 13:56
  • @kevlarr JS does in fact implement iterators/generators, but since Object.keys predates these it always returns an array. The question is really whether it is slower to collect keys and then iterate over them or to iterate and filter over uncollected keys. It seems like the overhead of collecting them is relatively small compared with looping over entries in JS land. – qubyte Jun 01 '17 at 21:14
  • @qubyte "ECMAScript specifies iterators/generators, but they still aren't widely supported in most runtimes" was what I meant... I honestly am curious about the implementation of `Object.keys` and whether it needs to iterate over *all* object properties (which if it does is no better than a `for` loop). If it doesn't, then yeah I think you're completely right - the overhead of collecting them and then iterating over them a *second time* is still probably way less than looping a single time over the entire prototype chain. – kevlarr Jun 02 '17 at 13:35
  • Oh whoops, I stand corrected.. Generators are pretty widely supported after all, just not in IE. (Would link to doc if stack overflow allowed links with * in them) – kevlarr Jun 02 '17 at 13:41
  • Probably worth noting that all of these _only_ get you enumerable properties, which can matter quite a bit. – Mike 'Pomax' Kamermans Apr 29 '22 at 16:42
513

By using a simple for..in loop:

for(var key in objects) {
    var value = objects[key];
}
Tatu Ulmanen
  • 123,288
  • 34
  • 187
  • 185
  • 93
    Be careful about the properties of the prototype object being inherited. See: hasOwnProperty() – olive Sep 21 '13 at 11:18
  • 117
    **If you are reading this answer, you should _definitely_ read [the other one](http://stackoverflow.com/a/16643074/641451)** – mgarciaisaia Dec 11 '15 at 23:35
  • 20
    If you're reading this answer and you might be possibly dealing with strings, you should definitely punch javascript in the face. –  Jan 28 '16 at 14:35
  • 1
    If you read the above answer and want to punch JavaScript in the face, try [lodash](https://lodash.com/) – slugmandrew Feb 19 '19 at 17:33
  • Should probably point out that this will NOT include properties which have their `enumerable` flag set to false. This - among other things - means you won't iterate over any class methods, but you will iterate over methods created in other ways. – rich remer Jul 28 '19 at 05:24
31

Here's a reusable function for getting the values into an array. It takes prototypes into account too.

Object.values = function (obj) {
    var vals = [];
    for( var key in obj ) {
        if ( obj.hasOwnProperty(key) ) {
            vals.push(obj[key]);
        }
    }
    return vals;
}
teh_senaus
  • 1,394
  • 16
  • 25
  • 15
    Modifying `Object` isn't much of a problem (`Object.keys` is a common shim), you are probably thinking of modifying the Object prototype. – sandstrom May 21 '13 at 08:13
  • Why would you need to test with `hasOwnProperty()`? How would the key be iterated over within the loop of that object hasn't got the property? – 1252748 Aug 25 '14 at 01:16
  • 4
    Google it @thomas, it's important. It might have properties from its prototype chain. – Joe Nov 19 '14 at 17:59
29

If you have access to Underscore.js, you can use the _.values function like this:

_.values({one : 1, two : 2, three : 3}); // return [1, 2, 3]
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
jichi
  • 6,333
  • 1
  • 31
  • 25
15

ES5 Object.keys

var a = { a: 1, b: 2, c: 3 };
Object.keys(a).map(function(key){ return a[key] });
// result: [1,2,3]
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Đọc truyện hay
  • 1,913
  • 21
  • 17
14

If you really want an array of Values, I find this cleaner than building an array with a for ... in loop.

ECMA 5.1+

function values(o) { return Object.keys(o).map(function(k){return o[k]}) }

It's worth noting that in most cases you don't really need an array of values, it will be faster to do this:

for(var k in o) something(o[k]);

This iterates over the keys of the Object o. In each iteration k is set to a key of o.

zzz
  • 356
  • 1
  • 4
  • 10
9

const myObj = { a:1, b:2, c:3 }

Get all values:

  • the shortest way:

    • const myValues = Object.values(myObj)
  • const myValues = Object.keys(myObj).map(key => myObj[key])

Carlos Andres
  • 12,740
  • 7
  • 18
  • 34
Anatoliy_Z
  • 129
  • 1
  • 4
6

You can loop through the keys:

foo = {one:1, two:2, three:3};
for (key in foo){
    console.log("foo["+ key +"]="+ foo[key]);
}

will output:

foo[one]=1
foo[two]=2
foo[three]=3
Josua Marcel C
  • 3,122
  • 6
  • 45
  • 87
ariera
  • 996
  • 8
  • 26
5

ECMA2017 onwards:

Object.values(obj) will fetch you all the property values as an array.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values

ishandutta2007
  • 16,676
  • 16
  • 93
  • 129
5

The question doesn't specify whether wanting inherited and non-enumerable properties also.

There is a question for getting everything, inherited properties and non-enumerable properties also, that Google cannot easily find.

If we are to get all inherited and non-enumerable properties, my solution for that is:

function getAllPropertyNames(obj) {
    let result = new Set();
    while (obj) {
        Object.getOwnPropertyNames(obj).forEach(p => result.add(p));
        obj = Object.getPrototypeOf(obj);
    }
    return [...result];
}

And then iterate over them, just use a for-of loop:

function getAllPropertyNames(obj) {
  let result = new Set();
  while (obj) {
    Object.getOwnPropertyNames(obj).forEach(p => result.add(p));
    obj = Object.getPrototypeOf(obj);
  }
  return [...result];
}

let obj = {
  abc: 123,
  xyz: 1.234,
  foobar: "hello"
};

for (p of getAllPropertyNames(obj)) console.log(p);
nonopolarity
  • 146,324
  • 131
  • 460
  • 740
3

For those early adapting people on the CofeeScript era, here's another equivalent for it.

val for key,val of objects

Which may be better than this because the objects can be reduced to be typed again and decreased readability.

objects[key] for key of objects
Ch.Idea
  • 578
  • 6
  • 8
3

Apparently - as I recently learned - this is the fastest way to do it:

var objs = {...};
var objKeys = Object.keys(obj);
for (var i = 0, objLen = objKeys.length; i < objLen; i++) {
    // do whatever in here
    var obj = objs[objKeys[i]];
}
dylnmc
  • 3,810
  • 4
  • 26
  • 42
3

use a polyfill like:

if(!Object.values){Object.values=obj=>Object.keys(obj).map(key=>obj[key])}

then use

Object.values(my_object)

3) profit!

user40521
  • 1,997
  • 20
  • 8
3
const object1 = {
  a: 'somestring',
  b: 42
};

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

// expected output:
// "a: somestring"
// "b: 42"
// order is not guaranteed
priya_21
  • 159
  • 1
  • 2
  • 15
1

I realize I'm a little late but here's a shim for the new firefox 47 Object.values method

Object.prototype.values = Object.prototype.values || function(obj) {
  return this.keys(obj).map(function(key){
    return obj[key];
  });
};
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Jamie
  • 90
  • 1
  • 3
1

Object.entries do it in better way.

  var dataObject = {"a":{"title":"shop"}, "b":{"title":"home"}}
 
   Object.entries(dataObject).map(itemArray => { 
     console.log("key=", itemArray[0], "value=", itemArray[1])
  })
Mustkeem K
  • 8,158
  • 2
  • 32
  • 43
1

Use: Object.values(), we pass in an object as an argument and receive an array of the values as a return value.

This returns an array of a given object own enumerable property values. You will get the same values as by using the for in loop but without the properties on the Prototype. This example will probably make things clearer:

function person (name) {
  this.name = name;
}

person.prototype.age = 5;

let dude = new person('dude');

for(let prop in dude) {
  console.log(dude[prop]);     // for in still shows age because this is on the prototype
}                              // we can use hasOwnProperty but this is not very elegant

// ES6 + 
console.log(Object.values(dude));
// very concise and we don't show props on prototype
Willem van der Veen
  • 33,665
  • 16
  • 190
  • 155
1

I think the easiest option is like this:

Object.keys(data).forEach(function (key, index) {
  var value = data[key];
  console.log(key, index, value);
});

For example, a runnable code is added here:

const user = {
    name: 'Alex',
    age: 30,
};

Object.keys(user).forEach(function (key, index) {
  var value = user[key];
  console.log(key, index, value);
});
Abrar Jahin
  • 13,970
  • 24
  • 112
  • 161
0

Here's a function similar to PHP's array_values()

function array_values(input) {
  var output = [], key = '';
  for ( key in input ) { output[output.length] = input[key]; }
  return output;
}

Here's how to get the object's values if you're using ES6 or higher:

Array.from(values(obj));
jaggedsoft
  • 3,858
  • 2
  • 33
  • 41
0

Compatible with ES7 even some browsers do not support it yet

Since , Object.values(<object>) will be built-in in ES7 &

Until waiting all browsers to support it , you could wrap it inside a function :

Object.vals=(o)=>(Object.values)?Object.values(o):Object.keys(o).map((k)=>o[k])

Then :

Object.vals({lastname:'T',firstname:'A'})
 // ['T','A']

Once browsers become compatible with ES7, you will not have to change anything in your code.

Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254
0

we can fetch data using three methods below

Use map function

data.map( item => { console.log(item) }

Use for loop

for( let i = 0; i < data.length; i++){
   console.log(item);
}

Use for in loop

for(key in data) {
    if(data.hasOwnProperty(key)) {
       const value = data[key];
       console.log(value);
    }
}
Jishnu V S
  • 8,164
  • 7
  • 27
  • 57
-2
var objects={...}; this.getAllvalues = function () {
        var vls = [];
        for (var key in objects) {
            vls.push(objects[key]);
        }
        return vls;
    }
Sudarshan Tanwar
  • 3,537
  • 3
  • 24
  • 39
-4

in ECMAScript5 use

 keys = Object.keys(object);

Otherwise if you're browser does not support it, use the well-known for..in loop

for (key in object) {
    // your code here
}
user278064
  • 9,982
  • 1
  • 33
  • 46
  • 17
    The question was asking for the values, not the keys. – zachelrath Oct 12 '12 at 19:19
  • 1
    @zachelrath You're right. - But this script is useful if you want to get the values because when you know the keys you are able to use `object[key]` to get the values in a loop. – fridojet Nov 14 '12 at 15:07
  • 2
    @fridojet But that can be done with `for..in` (and hasOwnProperty) so it doesn't really gain anything .. I wish that ECMAScript 5th defined `Object.pairs` (and `Object.items` for `[[key, value], ..]`), but alas, it does not. – user2246674 May 17 '13 at 06:01
-9

Now I use Dojo Toolkit because older browsers do not support Object.values.

require(['dojox/lang/functional/object'], function(Object) {
    var obj = { key1: '1', key2: '2', key3: '3' };
    var values = Object.values(obj);
    console.log(values);
});

Output :

['1', '2', '3']
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
rio
  • 34
  • 4
  • 5
    Strictly speaking, the array is not correct. You have an array of strings instead of an array of numbers. – qubyte Mar 23 '14 at 22:21
-11

use

console.log(variable)

and if you using google chrome open Console by using Ctrl+Shift+j

Goto >> Console

laaposto
  • 11,835
  • 15
  • 54
  • 71
Puneet
  • 137
  • 2
  • 2