Retrieving All Values ​​from a JavaScript Object

This is a function that I wrote to retrieve all the values ​​in a 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 a built-in way to get all the values ​​in an object? Something like this exists in java for HashMaps. I know that JS has a method for extracting all keys by executing Object.keys(obj) .

+7
javascript
source share
2 answers

Probably the most concise way to get an array of values ​​contained in 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 is no standardized way to get an array of object values.

For iteration, ES6 introduces a for..of loop that will iterate over the values ​​of the object:

continued from above:
 for (value of obj) { console.log(value); //1, 2, 3 } 

ES7 plans to introduce array methods , so the generation of an array of values ​​can be written as:

continued from above:
 values = [for (x of Object.keys(obj)) obj[x]]; 

If you already use an underscore, you can use the _.values method:

continued from above:
 _.values(obj); //[1, 2, 3] 

If you need an effective implementation for this utility function, lodash source :

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; } 
+12
source share

You can do this in new 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'}); 

Indeed, 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); 
+1
source share

All Articles