Home > Net >  why am i getting <1 empty item> when using mapping in JavaScript
why am i getting <1 empty item> when using mapping in JavaScript

Time:10-07

im using JSON to return an array.

Json:

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
  }, {
    "week": 4,
    "count": 3
  }],
  "netLost": 30,
  "netReturned": 200
}, {
  "week": 3,
  "lost": 8,
  "recovery_timespan": [{
    "week": 4,
    "count": 1
  }],
  "netLost": 50,
  "netReturned": 40
}];

i need to get the data into a array with lost,counts of recovery_timespan,netLost,netReturned.

Expected Output:

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

My approach:

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

console.log(result);

and this return array with <1 empty item>:

[ [ 10, 1, 0, <1 empty item>, 10, 20 ],
  [ 7, 1, 3, <1 empty item>, 30, 200 ],
  [ 8, 1, <1 empty item>, 50, 40 ] ]

Wha is the issue here?

CodePudding user response:

Why am i getting <1 empty item>

You have an extra comma:

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

Just remove it.

CodePudding user response:

You have an additional , after the nested map:

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

That creates a hole in the array. That's why you are seeing <1 empty item> in the output

console.log([1,,2])

CodePudding user response:

const res = data.map((el) => [
  el.lost,
  ...el.recovery_timespan.map((timespan) => timespan.count),
  /* extra comma here --> */, el.netLost,
  el.netReturned
])

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

CodePudding user response:

Not completly sure, but maybe try this.

...recovery_timespan.map(({count}) => count.count)
  • Related