将对象数组转换为另一个

时间:2019-07-11 17:49:52

标签: javascript

JS中的数组有问题。无法从一个数组转换为另一个数组,我正在尝试每个可以映射的东西,映射,过滤器,但是我做不到:(也许有另一种方法?我尝试了大约3个小时。 ..

如何从此数组转换:

[
      {
        "id": 1,
        "question": "Do you want to walk?",
        "answers": [
          {
            "id": 1,
            "answer": "Yes"
          }
        ]
      },
      {
        "id": 1,
        "question": "Do you want to walk?",
        "answers": [
          {
            "id": 2,
            "answer": "No"
          }
        ]
      },
      {
        "id": 1,
        "question": "Do you want to walk?",
        "answers": [
          {
            "id": 3,
            "answer": "Maybe"
          }
        ]
      },
      {
        "id": 1,
        "question": "Do you want to walk?",
        "answers": [
          {
            "id": 4,
            "answer": "Never"
          }
        ]
      }
    ]

对此:

[
      {
        "id": 1,
        "question": "Do you want to walk?",
        "answers": [
          {
            "id": 1,
            "answer": "Yes"
          },
          {
            "id": 2,
            "answer": "No"
          },
          {
            "id": 3,
            "answer": "Maybe"
          },
          {
            "id": 4,
            "answer": "Never"
          }
        ]
      }
    ]

2 个答案:

答案 0 :(得分:2)

因此,您要合并具有相同ID的所有对象,以使答案数组是所有对象的答案的列表?这听起来像是Array.reduce的工作:) Reduce将在整个数组中进行迭代并根据回调函数在每次迭代时如何操纵该输出值来输出新值。

arr.reduce((output, currentValue) => {
    const existing = output.find(element => {
        return element.id === currentValue.id;
    });
    if (existing) {
        existing.answers.push(...currentValue.answers);
    }
    else {
        output.push(currentValue);
    }
    return output;
}, []);

请注意,我在这里使用扩展运算符...currentValue.answers将答案数组扩展为多个要推送的参数。

答案 1 :(得分:2)

只需使用Array.reduce()创建一个基于ID的地图,然后在地图上使用Object.values()即可获得所需的结果:

let arr = [ { "id": 1, "question": "Do you want to walk?", "answers": [ { "id": 1, "answer": "Yes" } ] }, { "id": 1, "question": "Do you want to walk?", "answers": [ { "id": 2, "answer": "No" } ] }, { "id": 1, "question": "Do you want to walk?", "answers": [ { "id": 3, "answer": "Maybe" } ] }, { "id": 1, "question": "Do you want to walk?", "answers": [ { "id": 4, "answer": "Never" } ] } ];

 let result = Object.values(arr.reduce((acc,obj)=>{
    acc[obj.id] = acc[obj.id] || Object.assign({},obj);
    acc[obj.id].answers = (acc[obj.id].answers || []).concat(obj.answers);
    return acc;
 },{}));
 
 console.log(result);

相关问题