json 如何从所有子列表中获取id列表

velaa5lx  于 2023-05-30  发布在  其他
关注(0)|答案(2)|浏览(229)

我在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?

nnvyjq4y

nnvyjq4y1#

相反,您可以使用.reduce()和内部.map().filter()方法。内部的.map()方法会将给定答案数组中的所有对象转换为ids数组。.filter()方法将确保我们只抓取具有content"comment"的对象的id。外部reduce方法用于将内部.map()方法产生的所有数组整理成一个更大的数组。这是使用扩展语法将旧的累积数组与新Map的值合并来完成的。
参见以下示例:

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()

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);
f5emj3cl

f5emj3cl2#

请试试这个例子

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);

相关问题