从嵌套数组对象创建新数组

时间:2021-07-28 18:10:04

标签: javascript arrays reactjs

我想从 api 创建一个新数组,但我不知道如何创建它,我对循环每个数组感到非常困惑

这是每个数据

 const group_one = [
      {
        name: "smash",
        id: "012112"
      },
      {
        name: "ahlan wa sahlan",
        id: "123123"
      },
      {
        name: "ahh",
        id: "1231239"
      },
      {
        name: "laki",
        id: "21312"
      }
    ];
    
    const group_two = [
      {
        name: "ahh",
        id: "1231239"
      },
      {
        name: "laki",
        id: "21312"
      }
    ];
    
    const group_three = [
      {
        name: "smash",
        id: "012112"
      },
      {
        name: "ahlan wa sahlan",
        id: "123123"
      }
    ];
    

这是api的主要数据

const data = [
          {
            body: group_one,
            group_id: "01"
          },
          {
            body: grouop_two,
            group_id: "02"
          },
          {
            body: group_three,
            group_id: "03"
          }
        ];
    export default data;

我想像这样创建一个新数组,bcs我想创建一个包含数组中每个相同数据的 group_id 的新对象

const newArray = [
{
    name: "smash",
    id: "012112",
group_id: ["01","03"]
  },
  {
    name: "ahlan wa sahlan",
    id: "123123",
group_id: ["01","03"]
  },
  {
    name: "ahh",
    id: "1231239",
group_id: ["01","02"]
  },
  {
    name: "laki",
    id: "21312",
group_id: ["01","02"]
  }
];

有人可以帮我吗?与文章或代码。 谢谢你帮助我(对不起我的英语不好)

1 个答案:

答案 0 :(得分:1)

请看下面的注释代码:

const group01 = [
    {
        name: 'smash',
        id: '012112'
    },
    {
        name: 'ahlan wa sahlan',
        id: '123123'
    },
    {
        name: 'ahh',
        id: '1231239'
    },
    {
        name: 'laki',
        id: '21312'
    }
];

const group02 = [
    {
        name: 'ahh',
        id: '1231239'
    },
    {
        name: 'laki',
        id: '21312'
    }
];

const group03 = [
    {
        name: 'smash',
        id: '012112'
    },
    {
        name: 'ahlan wa sahlan',
        id: '123123'
    }
];

const data = [
    {
        body: group01,
        group_id: '01'
    },
    {
        body: group02,
        group_id: '02'
    },
    {
        body: group03,
        group_id: '03'
    }
];

function regroup(input) {
    // USE Map FOR EASIER ITEM HANDLING.
    const output = new Map();

    // LOOP MAIN DATA ARRAY.
    input.forEach(({body, group_id}) => {
        // LOOP EACH GROUP.
        body.forEach(({name, id}) => {
            // USE id TO GET AN ITEM FROM output OR CREATE A NEW ONE IF IT DOES NOT EXIST.
            const item = output.get(id) || {name, id, group_id: []};
            // PUSH CURRENT group_id TO THE RESPECTIVE ARRAY.
            item.group_id.push(group_id);
            // SAVE ITEM TO OUTPUT Map AGAIN.
            output.set(id, item);
        });
    });

    // RETURN OUTPUT.
    return Array.from(output.values());
}

const new_data = regroup(data);

console.log(new_data);