Alternative for Object.values โ€‹โ€‹()

I am looking for an alternative version for the Object.values() function.
As described , features are not supported in Internet Explorer.

When executing the following code example:

 var obj = { foo: 'bar', baz: 42 }; console.log(Object.values(obj)); // ['bar', 42] 

It works in both Firefox and Chrome, but the following error appears in IE11:

Object does not support property or method values

Here you can test it: Fiddle .

So what would be a quick fix?

+7
javascript browser internet-explorer ecmascript-6
Mar 16 '17 at 9:39 on
source share
3 answers

You can get an array of keys with Object.keys() and then use map() to get the values.

 var obj = { foo: 'bar', baz: 42 }; var values = Object.keys(obj).map(function(e) { return obj[e] }) console.log(values) 

With ES6, you can write this on a single line using arrow functions.

 var values = Object.keys(obj).map(e => obj[e]) 
+24
Mar 16 '17 at 9:41 on
source share
โ€” -

Since Object is a (not so) recent implementation, if you want to support all browsers (AKA IE8 and below), you need to create your own function:

 function objectValues(obj) { var res = []; for (var i in obj) { if (obj.hasOwnProperty(i)) { res.push(obj[i]); } } return res; } 

PS: Just noticed the ecmascript-6 tag. By the way, I keep this answer here, in case someone needs it.

+3
Mar 16 '17 at 9:45
source share

You can use polyfill:

 const valuesPolyfill = function values (object) { return Object.keys(object).map(key => object[key]); }; const values = Object.values || valuesPolyfill; console.log(values({ a: 1, b: 2, c: 3 })); 
+1
Mar 16 '17 at 9:43 on
source share



All Articles