Javascript数组对象操作



我有这个JavaScript数组/对象

[
{
"name": "A",
"selected_color": "Red"
},
{
"name": "B",
"selected_color": "Green"
},
{
"name": "C",
"selected_color": "Blue"
},
{
"name": "D",
"selected_color": "Red"
}
]

如何将其转换为以下格式?

[
{
"color": "Red",
"count": "2"
},
{
"color": "Green",
"count": "1"
},
{
"color": "Blue",
"count": "1"
}
]

我想根据'selected_color'键过滤值,'count'也将存储选择特定颜色的次数。

使用。reduce

const arr = [
{
"name": "A",
"selected_color": "Red"
},
{
"name": "B",
"selected_color": "Green"
},
{
"name": "C",
"selected_color": "Blue"
},
{
"name": "D",
"selected_color": "Red"
}
];
const op = arr.reduce((acc, cur) => {
const {selected_color} = cur;
const colorObj = acc.find(({color}) => color === selected_color );
if(colorObj) {
colorObj.count++;
} else {
acc.push({color: selected_color, count: 1});
}
return acc;

}, []);
console.log(op);
/*
[
{ color: 'Red', count: 2 },
{ color: 'Green', count: 1 },
{ color: 'Blue', count: 1 }
]
*/

你可以试试这个(使用groupBy):

let data = [
{
"name": "A",
"selected_color": "Red"
},
{
"name": "B",
"selected_color": "Green"
},
{
"name": "C",
"selected_color": "Blue"
},
{
"name": "D",
"selected_color": "Red"
}
];
let groupBy = (arr, key) => {
return arr.reduce((rv, x) => {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
};
let groupedData = groupBy(data, "selected_color");
let result = Object.keys(groupedData).map(color => ({'color': color, 'count': groupedData[color].length}) );
console.log(result);

相关内容

  • 没有找到相关文章

最新更新