我有一个像这样的数组
var myArray = [
{id: "1" , category: "cat1", "question1": "blue", "question2":"blue"},
{id: "1" , category: "cat1", "question1": "blue", "question2":"red"},
{id: "2" , category: "cat2", "question1": "blue", "question2":"blue"},
{id: "2" , category: "cat2", "question1": "red", "question2":"blue"}
];
我想计算每个问题结果的出现次数,并用这样的新对象创建新数组
var newArray = [
{category: "cat1", question:"question1", blue:2, red:0},
{category: "cat1", question:"question2", blue:1, red:1},
{category: "cat2", question:"question1", blue:1, red:1},
{category: "cat2", question:"question2", blue:2, red:0}
]
我尝试使用此功能
var result = myArray.reduce((r, {
category,
question1,
question2
}) => {
r.push({
category,
question1
}, {
category,
question2
})
return r;
}, [])
这是一个片段:
var myArray = [
{id: "1" , category: "cat1", "question1": "blue", "question2":"blue"},
{id: "1" , category: "cat1", "question1": "blue", "question2":"red"},
{id: "2" , category: "cat2", "question1": "blue", "question2":"blue"},
{id: "2" , category: "cat2", "question1": "red", "question2":"blue"}
];
var result = myArray.reduce((r, {
category,
question1,
question2
}) => {
r.push({
category,
question1
}, {
category,
question2
})
return r;
}, [])
console.log(result);

答案 0 :(得分:0)
您需要采用不同的方法,方法是使用哈希表和组合密钥进行访问。
var array = [{ id: "1", category: "cat1", "question1": "blue", "question2": "blue" }, { id: "1", category: "cat1", "question1": "blue", "question2": "red" }, { id: "2", category: "cat2", "question1": "blue", "question2": "blue" }, { id: "2", category: "cat2", "question1": "red", "question2": "blue" }],
result = Object.values(array.reduce((r, o) => {
['question1', 'question2'].forEach(question => {
var key = [o.category, question].join('|');
r[key] = r[key] || { category: o.category, question, blue: 0, red: 0 };
r[key][o[question]]++;
});
return r;
}, Object.create(null)));
console.log(result);

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

动态问题(蓝色/红色):
var array = [{ id: "1", category: "cat1", "question1": "blue", "question2": "blue" }, { id: "1", category: "cat1", "question1": "blue", "question2": "red" }, { id: "2", category: "cat2", "question1": "blue", "question2": "blue" }, { id: "2", category: "cat2", "question1": "red", "question2": "blue" }],
questions = new Set,
result = Object.values(array.reduce((r, o) => {
['question1', 'question2'].forEach(question => {
var key = [o.category, question].join('|');
if (!questions.has(o[question])) {
Object.values(r).forEach(p => p[o[question]] = 0);
questions.add(o[question]);
}
r[key] = r[key] || Object.assign({ category: o.category, question }, ...Array.from(questions, q => ({ [q]: 0 })));
r[key][o[question]]++;
});
return r;
}, Object.create(null)));
console.log(result);

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