问题描述
我试图使用for循环遍历条目数组并使用reduce方法,但是reduce在第一个条目之后返回,从不进入第二个,第三个等条目以将结果推入数组v。
有什么想法吗?
export const groupEventData = eventData => {
console.log(eventData)
// returns[{
// "id": "141",// "name": "00333",// "no_transmission": true,// "low_battery" :true,// },// {
// "id": "307",// "name": "01163",// "low_data_rate": true,// }
// ]
// Now let's group similar event types
let v = [];
let types = ["no_transmission","low_data_rate","low_battery"];
for (let x = 0; x <= types.length; x++) {
let data = eventData.reduce((acc,i) => {
if (!acc[i[types[x]]] && typeof i[types[x]] !== 'undefined') {
acc[i[types[x]]] = [i]
}
else if (Array.isArray(acc[i[types[x]]])) {
acc[i[types[x]]].push(i);
}
else if (typeof acc[i[types[x]]] === 'object') {
acc[i[types[x]]] = [acc[i[types[x]]]]
acc[i[types[x]]].push(i)
}
return acc;
},{});
// Doesn't add a property for the type if there are no data
Object.keys(data).length && v.push({ [types[x]: data });
return v;
};
}
解决方法
您的for循环中有return v
。尝试将其撞到紧靠其下方的大括号下方。现在,for循环仅迭代一次,然后返回一个值。
在下面为我工作:
const eventData = [
{"id": "141","name": "00333","no_transmission": true,"low_battery": true},{"id": "307","name": "01163","low_data_rate": true}
]
const type = 'bc'
const types = ["no_transmission","low_data_rate","low_battery"]
const groupEventData = (eventData,type) => {
let v = [];
for (let x = 0; x <= types.length; x++) {
let data = eventData.reduce((acc,i) => {
if (!acc[i[types[x]]] && typeof i[types[x]] !== 'undefined') {
acc[i[types[x]]] = [i]
}
else if (Array.isArray(acc[i[types[x]]])) {
acc[i[types[x]]].push(i);
}
else if (typeof acc[i[types[x]]] === 'object') {
acc[i[types[x]]] = [acc[i[types[x]]]]
acc[i[types[x]]].push(i)
}
return acc;
},{});
Object.keys(data).length && v.push({ [`${types[x]}_${type}`]: data });
};
return v;
}
console.log('groupEventData',groupEventData(eventData,type))