I\'m looking for an alternative version for the Object.values()
function.
As described here the function is not supported in Internet Explorer.
When
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]);
You can get array of keys using Object.keys(). This will work in IE also. Object.values() is not required at all to get values since we can use the keys obtained from Object.keys() to get values as below:
var obj = { foo: 'bar', baz: 42 };
var keyArray = Object.keys(obj);
for(var i = 0; i < keyArray.length; i++)
console.log(obj[keyArray[i]]);
You can use a 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 }));
var x = {Name: 'John', Age: 30, City: 'Bangalore'};
Object.prototype.values = function(obj) {
var res = [];
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
res.push(obj[i]);
}
}
return res;
};
document.getElementById("tag").innerHTML = Object.values(x)
<p id="tag"></p>
As I didn't found an answer for my needs:
var obj = { foo: 'bar', baz: 42 };
console.log(obj[Object.keys(obj)[0]]) // bar
console.log(obj[Object.keys(obj)[1]]) // 42
Using the possibility of objects to adress them per literal.