This is the function I wrote to retrieve all the values in an given object.
function getValues(data){
var keys = Object.keys(data);
var values = [];
for(var i = 0, l = keys.length, key; i< l; i++){
key = keys[i];
values.push(data[key]);
}
return values;
}
Is there any builtin way to retrieve all the values in an object? Something like this exists in java for HashMaps. I know JS has a method for retrieving all the keys by doing Object.keys(obj)
.
Probably the most concise way of getting an array of the values contained within an object is to use Object.keys
and Array.prototype.map
:
obj = {
a: 1,
b: 2,
c: 3
};
values = Object.keys(obj).map(function (key) {
return obj[key];
});
Otherwise there's no standardized way of getting an array of an object's values.
For iterating, ES6 introduces a for..of
loop which will iterate through an object's values:
for (value of obj) {
console.log(value); //1, 2, 3
}
ES7 is slated to introduce array comprehensions, so generating the values array could be written as:
continued from above:values = [for (x of Object.keys(obj)) obj[x]];
If you're already using underscore, you can use the _.values
method:
_.values(obj); //[1, 2, 3]
If you just want an efficient implementation for this utility function, the lodash source is:
lodash.js v2.4.1 lines 2891-2914/**
* Creates an array composed of the own enumerable property values of `object`.
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The object to inspect.
* @returns {Array} Returns an array of property values.
* @example
*
* _.values({ 'one': 1, 'two': 2, 'three': 3 });
* // => [1, 2, 3] (property order is not guaranteed across environments)
*/
function values(object) {
var index = -1,
props = keys(object),
length = props.length,
result = Array(length);
while (++index < length) {
result[index] = object[props[index]];
}
return result;
}
You could do this, in newer Browsers:
Object.defineProperty(Object.prototype, 'values', {
get:function(){
return function(o){
var a = [];
for(var i in o){
a.push(o[i]);
}
return a;
}
}
});
var arrayOfValues = Object.values({a:'A',b:'B',c:'C'});
Really, I would just do:
function objectValues(obj, inherited){
var a = [];
for(var i in obj){
var v = obj[i];
if(inherited){
a.push(v);
}
else if(obj.hasOwnProperty(i)){
a.push(v);
}
}
return a;
}
var notInheritedArrayOfValues = objectValues({a:'A',b:'B',c:'C'});
var inheritedArrayOfValues = objectValues({a:'A',b:'B',c:'C'}, true);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With