我有一个对象数组,我想使用Reduce转换为对象:
const results = [{
person: "person1",
choice: 0,
questionId: "a"
},
{
person: "person1",
choice: 1,
questionId: "b"
},
{
...
}
];
并希望返回具有此预期输出的对象:
{
results: [
person1: {
a: [1, 0, 0, 0],
b: [0, 1, 0, 0],
c: [0, 0, 0, 0]
},
person2: {
a: [0, 0, 0, 0],
b: [0, 0, 1, 0],
c: [0, 1, 0, 0]
},
person3: {
a: [0, 0, 0, 1],
b: [0, 0, 0, 0],
c: [0, 0, 0, 0]
}
]
}
每个a:[...]指的是"选择" [0,1,2,3]每个"问题" [A,B,C]。 Person应该是索引,而questionId可能是变量的(它可能包括" d"例如")。
我的尝试:
const results = [{
person: "person1",
choice: 0,
questionId: "a"
},
{
person: "person1",
choice: 1,
questionId: "b"
},
{
person: "person2",
choice: 2,
questionId: "c"
},
{
person: "person2",
choice: 3,
questionId: "b"
},
{
person: "person3",
choice: 2,
questionId: "a"
}
];
people = ["person1", "person2", "person3"];
let responses = results.reduce((init, response) => {
switch (response.segment) {
case people[0]:
init[people[0]][response.questionId].push(response.choice[0])
break;
case people[1]:
init[people[1]][response.questionId].push(response.choice[0])
break;
case people[2]:
init[people[2]][response.questionId].push(response.choice[0]);
break;
default:
break;
}
return init;
});
console.log(responses);

我不确定如何启动对象以允许附加问题并获得我需要的格式?
非常感谢。
答案 0 :(得分:1)
假设在您的输出中,您的意思是{ "person1": {...}, ...}
而不是[ "person1": {...}, ...]
(后者是语法错误),您可以使用reduce执行此操作,如下所示:
const results = [
{ person: "person1", choice: 0, questionId: "a" },
{ person: "person1", choice: 1, questionId: "b" },
{ person: "person2", choice: 2, questionId: "c" },
{ person: "person2", choice: 3, questionId: "b" },
{ person: "person3", choice: 2, questionId: "a" }
];
// create an array of all unique questionIds found in the results array
var questionIds = Array.from(new Set(results.map(result => result.questionId)));
console.log(questionIds);
var resultsObj = {
results: results.reduce((res, {person, questionId, choice}) => {
// if person hasn't been created yet, create them
if (!res[person]) {
// need to do .map here instead of outside so we get fresh array references for each person
res[person] = Object.assign({}, ...questionIds.map(id => ({[id]: [0,0,0,0]})));
}
// log a 1 in the correct slot for the answer given
res[person][questionId][choice] = 1;
return res;
}, {})
};
console.log(resultsObj);