Home > database >  JavaScript: Extract values of a specific key out of key-value array and store them in a new array
JavaScript: Extract values of a specific key out of key-value array and store them in a new array

Time:01-09

I have an' multidimensional key-value array like this:

'[[
{"_time":"2022-01-03T00:00:00Z","_value":10.70140000000014,"ts":1641168000000},
{"_time":"2022-01-04T00:00:00Z","_value":13.002499999999767,"ts":1641254400000},
{"_time":"2022-01-05T00:00:00Z","_value":16.171700000000182,"ts":1641340800000},
{"_time":"2022-01-06T00:00:00Z","_value":17.48929999999981,"ts":1641427200000},
]]'

and I need the values from each of them in a new variable in this way:

[10.70140000000014,13.002499999999767,16.171700000000182,17.48929999999981]

I tried it with map but that do not match my needs:

function getPreparedData(data) {
  if (data) {
  return data[0].map(elm => ({
      a: elm._value
  }));
  }
   return [];
};

How can I solve this?

Thanks

Frank

CodePudding user response:

In your example, the function getPreparedData is returning array of objects. You actually want to return an array of values (where values are just the value of the _value property)

const data = [[
{"_time":"2022-01-03T00:00:00Z","_value":10.70140000000014,"ts":1641168000000},
{"_time":"2022-01-04T00:00:00Z","_value":13.002499999999767,"ts":1641254400000},
{"_time":"2022-01-05T00:00:00Z","_value":16.171700000000182,"ts":1641340800000},
{"_time":"2022-01-06T00:00:00Z","_value":17.48929999999981,"ts":1641427200000},
]];

function getPreparedData(data) {
  return data[0].map(elm => elm._value)
};

const res = getPreparedData(data);
console.log(res);

  •  Tags:  
  • Related