如何将代码重写为对象数组

时间:2019-07-11 13:25:36

标签: javascript arrays object

我有这样的代码:

var data =[
  [{qText:"A"},{qText:"type1"},{qText: 5}],
  [{qText:"A"},{qText:"type2"},{qText: 3}],
  [{qText:"A"},{qText:"type3"},{qText: 5}],
  .......

 ]

我该如何重写它,这样就可以了?

var data = [
  { team: "A", type1: "5", type2: "3", type3: "5" },
  { team: "B", type1: "0", type2: "3", type3: "3" },
  { team: "C", type1: "8", type2: "2", type3: "4" },
];

1 个答案:

答案 0 :(得分:0)

您可以使用对象来分解数组,并在结果集中找到相同的团队,或者添加一个新对象。然后将字符串值分配给给定的键。

var data = [[{ qText: "A" }, { qText: "type1" }, { qText: 5 }], [{ qText: "A" }, { qText: "type2" }, { qText: 3 }], [{ qText: "A" }, { qText: "type3" }, { qText: 5 }], [{ qText: "B" }, { qText: "type1" }, { qText: 0 }], [{ qText: "B" }, { qText: "type2" }, { qText: 3 }], [{ qText: "B" }, { qText: "type3" }, { qText: 3 }], [{ qText: "C" }, { qText: "type1" }, { qText: 8 }], [{ qText: "C" }, { qText: "type2" }, { qText: 2 }], [{ qText: "C" }, { qText: "type3" }, { qText: 4 }]],
    result = data.reduce((r, [{ qText: team }, { qText: key }, { qText: value }]) => {
        var temp = r.find(o => o.team === team);
        if (!temp) r.push(temp = { team });
        temp[key] = value.toString();
        return r;
    }, []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }