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?
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?
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.
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.
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
.
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 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 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
shimFinally, 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]));
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.
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]
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.
ES5 Object.keys
var a = { a: 1, b: 2, c: 3 };
Object.keys(a).map(function(key){ return a[key] });
// result: [1,2,3]
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
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);
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
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']
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']