将 id 引用到数组中并将其映射

时间:2021-08-01 14:52:40

标签: javascript reactjs

我有这样一个数组。

[
  {
    id: 1,
    title: "one",
    cats: [],
  },
  {
    id: 2,
    title: "two",
    cats: [{ id: 3 }, { id: 4 }],
  },
  {
    id: 3,
    title: "sub 1",
    cats: [],
  },
  {
    id: 4,
    title: "sub 2",
    cats: [],
  },
];


如何将 id 3 和 4 正确引用到嵌套的猫数组中。

我需要实现以下目标。

我需要将列表显示为按钮,但嵌套为下拉列表。

示例

one.title
two.title
  sub1.title
  sub2.title

我不想将 id 3 和 4 数据(如标题)放入嵌套数组中,因为路由器将 ID 作为参数,所以基本上当我单击 sub1 时,它应该显示来自 id-3 的数据。

请帮助我理解这一点,因为我是新手。 谢谢。

1 个答案:

答案 0 :(得分:0)

你可以使用这个函数来格式化你的数组:

  const formatArray = arr =>
    arr.map(item => {
      if (item.cats.length === 0) {
        return item;
      } else {
        const itemtFormatted = { ...item };
        itemtFormatted.cats = item.cats.map(cat =>
          arr.find(e => e.id === cat.id)
        );
        return itemtFormatted;
      }
    });

您可以在这里查看:https://jsfiddle.net/x9o6dkum/