簡體   English   中英

如何從所有子列表中獲取 id 列表 - Javascript

[英]How to get a list of ids from all child lists - Javascript

我在 json / javascript 中有以下結構

{
  "comments": [
    {
      "id": 1,
      "content": "comment",
      "answers": []
    },
    {
      "id": 2,
      "content": "comment",
      "answers": [
        {
          "id": 25,
          "content": "comment"
        }
      ]
    },
    {
      "id": 3,
      "content": "comment",
      "answers": [
        {
          "id": 72,
          "content": "comment"
        },
        {
          "id": 105,
          "content": "comment"
        }
      ]
    },
    {
      "id": 4,
      "content": "comment",
      "answers": []
    }
  ]
}

我需要獲取一個包含每個響應類型注釋的 id 的數組,例如

[25, 72, 105]

注意:我可以只使用mapreducefilter

到目前為止我所取得的只是一個有一些答案的評論過濾器

const commentsWithAnswers = comments.filter(
  (comment) => comment.answers.length !== 0
)

但我無法將每個答案的 id 提取到數組中

誰能幫我這個?

提前致謝

相反,您可以將.reduce()與內部.map().filter()方法一起使用。 內部.map()方法會將給定答案數組中的所有對象轉換為ids數組。 .filter()方法將確保我們只獲取具有"comment" content的對象的 id。 外部reduce方法用於將內部.map()方法產生的所有arrays整理成一個更大的數組。 這是使用擴展語法將舊的累積數組與新映射的值合並來完成的。

請參見下面的示例:

 const obj = { "comments": [ { "id": 1, "content": "comment", "answers": [] }, { "id": 2, "content": "comment", "answers": [ { "id": 25, "content": "comment" } ] }, { "id": 3, "content": "comment", "answers": [ { "id": 72, "content": "comment" }, { "id": 105, "content": "comment" } ] }, { "id": 4, "content": "comment", "answers": [] } ] } const res = obj.comments.reduce( (acc, {id, answers, content}) => [...acc, ...answers.filter(({content}) => content === "comment").map(({id}) => id)], []); console.log(res);

話雖如此,我更喜歡將.flatMap()用於這種類型的事情,而不是 .reduce .reduce()

 const obj = { "comments": [ { "id": 1, "content": "comment", "answers": [] }, { "id": 2, "content": "comment", "answers": [ { "id": 25, "content": "comment" } ] }, { "id": 3, "content": "comment", "answers": [ { "id": 72, "content": "comment" }, { "id": 105, "content": "comment" } ] }, { "id": 4, "content": "comment", "answers": [] } ] } const res = obj.comments.flatMap(({id, answers}) => answers.filter(({content}) => content === "comment").map(({id}) => id)); console.log(res);

請試試這個例子

 const data = { comments: [ { id: 1, content: "comment", answers: [], }, { id: 2, content: "comment", answers: [ { id: 25, content: "comment", }, ], }, { id: 3, content: "comment", answers: [ { id: 72, content: "comment", }, { id: 105, content: "comment", }, ], }, { id: 4, content: "comment", answers: [], }, ], }; const output = data.comments.map((entry) => entry.answers.map((item) => item.id)).flat(); const anotherOutput = data.comments.map(({ id }) => id); console.log(output, anotherOutput);

暫無
暫無

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

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