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

using map with filter array JavaScript

i have a json and need to extract data to array.

const data = [{
  "week": 1,
  "lost": 10,
  "recovery_timespan": [{
    "week": 2,
    "count": 1
  }, {
    "week": 3,
    "count": 0
  }],
   "netLost": 10,
  "netReturned": 20
}, {
  "week": 2,
  "lost": 7,
  "recovery_timespan": [{
    "week": 3,
    "count": 1
  }],
  "netLost": 30,
  "netReturned": 200
}, {
  "week": 3,
  "lost": 8,
  "recovery_timespan":"",
  "netLost": 50,
  "netReturned": 40
}];

Expected output: lost,count in recovery_timespan,netLost , netReturned.

[ [ 10, 1, 0, 10, 20 ], [ 7, 1, 30, 200 ], [ 8, 50, 40 ] ]

As you can see expected output, last recovery_timespan does not contain any data and it just shows as "".so i need to ignore it.

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

My approach:

const result = data.map(({lost, recovery_timespan,netLost,netReturned}) => [
  lost,
  ...recovery_timespan.map(({count}) => count),
  netLost,netReturned
]);

My code breaks when "recovery_timespan" is "". How can i add a filter along with map to filter that part and make my code work?

>Solution :

It’s just a matter of checking if it’s string or not, but you can short circuit

const result = data.map(({lost, recovery_timespan,netLost,netReturned}) => [
  lost,
  ...(recovery_timespan || []).map(({count}) => count),
  netLost,netReturned
]);
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