代码之家  ›  专栏  ›  技术社区  ›  hncl

JavaScript使用相同的键合并数组对象

  •  0
  • hncl  · 技术社区  · 2 年前

    我有一个包含多个对象的数组,其中一些对象具有相同的键(Question和QuestionId),例如:

        var jsonData = [
                {
                    Question: "Was the training useful?",
                    QuestionId: 1,
                    myData: [{ name: 'No', value: 1 }] },
                {
                    Question: "Was the training useful?",
                    QuestionId: 1 ,
                    myData: [{ name: 'Yes', value: 1 }]
            }];
    

    如何将这些对象合并为一个预期输出:

          var jsonData = [
            {
                Question: "Was the training useful?",
                QuestionId: 1,
                myData: [{ name: 'No', value: 1 },
                         { name: 'Yes', value: 1 }] 
              }];
    
    2 回复  |  直到 2 年前
        1
  •  2
  •   pilchard    2 年前

    var jsonData = [{
        Question: "Was the training useful?",
        QuestionId: 1,
        myData: [{
          name: 'No',
          value: 1
        }]
      },
      {
        Question: "Was the training useful?",
        QuestionId: 1,
        myData: [{
          name: 'Yes',
          value: 1
        }]
      }
    ];
    
    const result = Object.values(jsonData.reduce((acc, obj) => {
      if (!acc[obj.QuestionId]) {
        acc[obj.QuestionId] = obj;
      } else {
        acc[obj.QuestionId].myData = acc[obj.QuestionId].myData.concat(obj.myData);
      }
      return acc;
    }, {}));
    
    console.log(result);
        2
  •  0
  •   Sereyn    2 年前
    function mergeData(data) {
      const acc = {}
      data.forEach(x => {
        const id = x.QuestionId
        if (!acc[id]) acc[id] = x
        else acc[id].myData = acc[id].myData.concat(x.myData)
      })
      return Object.values(acc)
    }
    
        3
  •  0
  •   Chris Strickland    2 年前

    可以使用forEach创建一个对象,其中键是问题ID,然后在对象上再次使用forEach。键将值从该对象传输到新数组。

    var jsonData = [{
      Question: "Was the training useful?",
      QuestionId: 1,
      myData: [{ name: 'No', value: 1 }] 
    }, {
      Question: "Was the training useful?",
      QuestionId: 1 ,
      myData: [{ name: 'Yes', value: 1 }]
    }];
    
    var temp = {};
    jsonData.forEach(x=>{
      if(!temp[x.QuestionId]) {temp[x.QuestionId] = x;} 
      else {temp[x.QuestionId].myData.push(x.myData);}
    });
    
    var arr = [];
    Object.keys(temp).forEach(x=>{arr.push(temp[x]);});
    
    console.log(arr);