gpt4 book ai didi

javascript - 计算新数组映射中的项目数

转载 作者:行者123 更新时间:2023-11-28 16:52:40 24 4
gpt4 key购买 nike

我有一个大数组,然后我为某些字段提取唯一的键/值对,如下所示:

    let dropdown = {};
dropdown.make = [...new Set(vehicles.map((item) => item.Make))];
dropdown.model = [...new Set(vehicles.map((item) => item.Model))];
return dropdown;

这可以正常工作,并将返回新对象中品牌和型号的所有唯一值。我怎样才能让它返回每个项目的计数?

因此,如果 dropdown.model 返回一个包含 3 个项目的数组,是否可以获取这三个项目中每一项旁边的总计数,以查看这三个项目中每一项的原始数组中有多少条记录?

目前,输出看起来像这样:

{
"dropdown": {
"make": [
"Kia"
],
"model": [
"Carens",
"Ceed"
],
"colour": [
"Silver",
"White",
"Black"
]
}
}

最好的输出方式是什么,格式类似于:

{
"dropdown": {
"make": [
{
"name": "Kia",
"count": 5
}
],
"model": [
{
"name": "Carens",
"count": 2
},
{
"name": "Ceed",
"count": 3
}
],
"colour": [
{
"name": "Silver",
"count": 2
},
{
"name": "Black",
"count": 3
}
]
}
}

最佳答案

let vehicles = [
{make: 'x', model: 'a'},
{make: 'x', model: 'b'},
{make: 'x', model: 'a'},
{make: 'y', model: 'c'},
{make: 'y', model: 'c'},
{make: 'x', model: 'a'},
{make: 'x', model: 'd'},
{make: 'z', model: 'd'},
]

let makes = Object.values(vehicles.reduce((makes, {make}) => {
makes[make] = makes[make] || {name: make, count: 0};
makes[make].count++;
return makes;
}, {}));

let models = Object.values(vehicles.reduce((models, {model}) => {
models[model] = models[model] || {name: model, count: 0};
models[model].count++;
return models;
}, {}));

let dropdown = {makes, models};

console.log(dropdown);

编辑,通用函数:

let vehicles = [
{make: 'x', model: 'a'},
{make: 'x', model: 'b'},
{make: 'x', model: 'a'},
{make: 'y', model: 'c'},
{make: 'y', model: 'c'},
{make: 'x', model: 'a'},
{make: 'x', model: 'd'},
{make: 'z', model: 'd'},
];

let vehicleReduce = (vehicles, key) =>
Object.values(vehicles.reduce((acc, vehicle) => {
let value = vehicle[key];
acc[value] = acc[value] || {name: value, count: 0};
acc[value].count++;
return acc;
}, {}));

let makes = vehicleReduce(vehicles, 'make');
let models = vehicleReduce(vehicles, 'model');
let dropdown = {makes, models};
console.log(dropdown);

最后,这是解构动态键的方法:

let key = 'make';
let {[key]: value} = {make: 'x'};
console.log(value, '===', 'x');

let vehicles = [
{make: 'x', model: 'a'},
{make: 'x', model: 'b'},
{make: 'x', model: 'a'},
{make: 'y', model: 'c'},
{make: 'y', model: 'c'},
{make: 'x', model: 'a'},
{make: 'x', model: 'd'},
{make: 'z', model: 'd'},
];

let vehicleReduce = (vehicles, key) =>
Object.values(vehicles.reduce((acc, {[key]: value}) => {
acc[value] = acc[value] || {name: value, count: 0};
acc[value].count++;
return acc;
}, {}));

let makes = vehicleReduce(vehicles, 'make');
let models = vehicleReduce(vehicles, 'model');
let dropdown = {makes, models};
console.log(dropdown);

关于javascript - 计算新数组映射中的项目数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59738837/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com