Get key value array object


#1

Hi all

I have a plunker here - https://plnkr.co/edit/gZZ6uh9FZZsTILC1dZVV?p=preview

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


#2

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

maxVal.push(key)

should becomethis line

maxVal.push(data[i][key])

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


#3

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: {
        "one":4306,
        "two":2465,
        "three":2299,
        "four":988,
        "five":554,
        "six":1841
      },
      "date":"2015-05-31"
   },
...
for(var i=0; i<data.length; i++) {
  for (var key in data[i].values) {
    maxVal.push(key);
  }
}

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

#4

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.