I'm looking for an alternative version for the Object.values() function.
As described here the function is not supported in Internet Explorer.
When executing the following example code:
var obj = { foo: 'bar', baz: 42 };
console.log(Object.values(obj)); // ['bar', 42]
It works in both, Firefox and Chrome, but throws the following error in IE11:
Object doesn't support property or method "values"
Here you can test it: Fiddle.
So, what would be a quick fix?
You can get array of keys with Object.keys() and then use map() to get 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 in one line using arrow-functions.
var values = Object.keys(obj).map(e => obj[e])
Object.values() is part of the ES8(June 2017) specification. Using Cordova, I realized Android 5.0 Webview doesn't support it. So, I did the following, creating the polyfill function only if the feature is not supported:
if (!Object.values) Object.values = o=>Object.keys(o).map(k=>o[k]);
Since Object is a (not so) recent implementation, if you want to support all browsers (AKA IE11 and below), then you need to create your own function:
function objectValues(obj) {
var res = [];
for (var i in obj) {
if (Object.prototype.hasOwnProperty.call(obj, i)) {
res.push(obj[i]);
}
}
return res;
}
PS: Just noticed the ecmascript-6 tag. Btw I keep this answer here, just in case someone needs it.