Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
386 views
in Technique[技术] by (71.8m points)

javascript - 请问有什么方法可以将这些数据处理成所需的格式?(Is there any way to manipulate this data into the desired format please?)

I would like to go from this:(我想从这里开始:)

[ { 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 } ] To this:(对此:) [ { 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] } ] I will need to do this manipulation for each usersID.(我将需要对每个usersID进行此操作。) Thank you(谢谢)   ask by singh3244 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

you need to manipulate your array to get the result.(您需要操纵数组以获得结果。)

You can try like below,(您可以尝试以下操作,) 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))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...