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;
}
You can also modify this for Object.keys() and Object.entries() easily.
PS: Just noticed the ecmascript-6 tag. Btw I keep this answer here, just in case someone needs it.
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)
I know it is a old topic. I was playing arround and just want to add another implementation.
It is simply the map version with the map itself implemented with a reduce :
It does the job but it has something that bother me. The reducer function uses obj and the obj was not injected in it. We should avoid global variable inside functions and make our functions more testable. So I do prefer this version with a reducer function helper that takes the obj as parameter an return the actual reducer function . It becomes:
let obj = { foo: 'bar', baz: 42 };
// reducer function helper take obj and return the actual reducer function
let reducerFuncHelper= obj => (acc, key) => {
acc.push(obj[key]);
return acc;
}
//much better
const valueArray = Object.keys(obj).reduce(reducerFuncHelper(obj), []);
console.log(valueArray);
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]]);