Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

How can I solve this?

Thanks

Frank

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading