Merge duplicate objects in array of objects

后端 未结 3 1118
心在旅途
心在旅途 2020-11-29 06:03

I have below array of objects,

var data = [
    {
        label: \"Book1\",
        data: \"US edition\"
    },
    {
        label: \"Book1\",
        data:         


        
3条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-29 06:44

    I came across the same situation and I was hoping to use the Set instead of mine here

    const data = [
      {
        label: "Book1",
        data: "US edition"
      },
      {
        label: "Book1",
        data: "UK edition"
      },
      {
        label: "Book2",
        data: "CAN edition"
      },
      {
        label: "Book3",
        data: "CAN edition"
      },
      {
        label: "Book3",
        data: "CANII edition"
      }
    ];
    
    const filteredArr = data.reduce((acc, current) => {
      const x = acc.find(item => item.label === current.label);
      if (!x) {
        const newCurr = {
          label: current.label,
          data: [current.data]
        }
        return acc.concat([newCurr]);
      } else {
        const currData = x.data.filter(d => d === current.data);
        if (!currData.length) {
          const newData = x.data.push(current.data);
          const newCurr = {
            label: current.label,
            data: newData
          }
          return acc;
        } else {
          return acc;
        }
        
      }
    }, []);
    
    console.log(filteredArr);

提交回复
热议问题