请问有什么方法可以将这些数据处理成所需的格式?

时间:2019-11-29 00:24:01

标签: javascript json

我想从这里开始:

[ { compID: 1, problem: 1, usersID: 1, completed: 1 },
  { compID: 1, problem: 1, usersID: 5, completed: 1 },
  { compID: 1, problem: 2, usersID: 1, completed: 0 },
  { compID: 1, problem: 2, usersID: 5, completed: 1 },
  { compID: 1, problem: 3, usersID: 1, completed: 1 },
  { compID: 1, problem: 3, usersID: 5, completed: 0 },
  { compID: 1, problem: 4, usersID: 1, completed: 0 },
  { compID: 1, problem: 4, usersID: 5, completed: 1 },
  { compID: 1, problem: 5, usersID: 1, completed: 1 },
  { compID: 1, problem: 5, usersID: 5, completed: 0 } ]

为此:

[ { compID: 1, problem: [1,2,3,4,5], usersID: 1, completed: [1,0,1,0,1] },

  { compID: 1, problem: [1,2,3,4,5], usersID: 5, completed: [1,1,0,1,0] } ]

我将需要对每个usersID进行此操作。 谢谢

1 个答案:

答案 0 :(得分:1)

您需要操纵数组以获得结果。您可以尝试以下方式

 var data = [ { compID: 1, problem: 1, usersID: 1, completed: 1 },
  { compID: 1, problem: 1, usersID: 5, completed: 1 },
  { compID: 1, problem: 2, usersID: 1, completed: 0 },
  { compID: 1, problem: 2, usersID: 5, completed: 1 },
  { compID: 1, problem: 3, usersID: 1, completed: 1 },
  { compID: 1, problem: 3, usersID: 5, completed: 0 },
  { compID: 1, problem: 4, usersID: 1, completed: 0 },
  { compID: 1, problem: 4, usersID: 5, completed: 1 },
  { compID: 1, problem: 5, usersID: 1, completed: 1 },
  { compID: 1, problem: 5, usersID: 5, completed: 0 } ]

var res ={};

data.map(d => {
  if(res[d.usersID]) {
    res[d.usersID].problem.push(d.problem);
    res[d.usersID].completed.push(d.completed);
  } else {
    res[d.usersID] = {compID: d.compID, problem: [d.problem], usersID: d.usersID, completed: [d.completed]  }
  }
})

console.log(Object.values(res))