簡體   English   中英

為什么我在 JavaScript 中使用映射時得到 <1 個空項目>

[英]why am i getting <1 empty item> when using mapping in JavaScript

我使用 JSON 返回一個數組。

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
}];

我需要將數據放入一個數組中,其中包含lostcounts of recovery_timespannetLostnetReturned的計數。

預計 Output:

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

我的方法:

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

console.log(result);

這個返回數組<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 ] ]

這里的問題是什么?

在嵌套的 map 之后還有一個,

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

這會在數組中創建一個 這就是為什么您在 output 中看到<1 empty item>

 console.log([1,,2])

為什么我得到 <1 個空項目>

你有一個額外的逗號:

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

只需將其刪除。

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 ] ]

不完全確定,但也許試試這個。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM