Get key value array object


Hi all

I have a plunker here -

I have simple objects in an array.

I just trying to get values from the keys and put them in an array.

I can get the keys but how do I get the values


You can access object properties the same way you can access array elements, using the square brackets notation. So this line


should becomethis line


The result will be a flattened list of the desired object values.


The easy way to get the keys is with Object.keys(data)

And likewise, the easy way to get the values is with Object.values(data)

It is better though to have your data values stored in a separate object from the date, as that is not only better organised, it makes for easier code too:

var data = [
      values: {
for(var i=0; i<data.length; i++) {
  for (var key in data[i].values) {

If I were to get the max value from that data, I would make use of the filter/map/reduce methods.

Filter isn't needed at this stage, so that can be left out of this solution leaving us with map and reduce:

function flatten(arr, values) {
  arr = arr.concat(values);
  return arr;

var maxVal = Math.max.apply(Math, data
  .map(item => Object.values(item.values))
  .reduce(flatten, [])
console.log(maxVal); // 4378


And if you want an array of max values, that's even easier, with:

var maxVal = data
  .map(item => Object.values(item.values))
  .map(values => Math.max.apply(Math, values));
console.log(maxVal); // [4306, 4378, 3404]

closed #5

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.