0

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.

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?

2
  • Want to skip records when recovery_timespan is empty? Commented Oct 10, 2022 at 18:31
  • yes, my code breaks when there is "" for recovery_timespan. Commented Oct 10, 2022 at 18:42

1 Answer 1

3

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
]);
Sign up to request clarification or add additional context in comments.

2 Comments

this works. Can you please explain recovery_timespan || [ ] part?
it's a classic (although not necessarily precise) shortcut because OR expressions are evaluated left to right and in a lazy way. That means if recovery_timespan is truthy then it won't even get to evaluate the [] part. However, if recovery_timespan is falsy then the second part of the expression will evaluate to return the result []. falsy is 0, "", false etc

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.