gpt4 book ai didi

javascript - 计算每个值在数组中有多少个对象

转载 作者:行者123 更新时间:2023-11-30 06:57:43 25 4
gpt4 key购买 nike

我有这个数组:

var markers = [
{
"type":"Chocolate",
"name":"KitKat",
"group":"candy",
"icon":"candy",
"coords":[5246,8980],
},
{
"type":"Fruit",
"name":"Orange",
"group":"fruits",
"icon":"fruis",
"coords":[9012,5493],
},
{
"type":"Fruit",
"name":"Banana",
"group":"fruits",
"icon":"fruis",
"coords":[9012,5493],
},
{
"type":"Food",
"name":"Rice",
"group":"foods",
"icon":"foods",
"coords":[6724,9556],
},
{
"type":"Food",
"name":"Meat",
"group":"foods",
"icon":"foods",
"coords":[6724,9556],
},
{
"type":"Food",
"name":"Beam",
"group":"foods",
"icon":"foods",
"coords":[6724,9556],
},
{
"type":"Liquid",
"name":"Water",
"group":"liquids",
"icon":"liquids",
"coords":[6724,9556],
},
{
"type":"Liquid",
"name":"Coffe",
"group":"liquids",
"icon":"liquids",
"coords":[6724,9556],
},
]

我想计算每个组在此数组中有多少项。

我设法用这个数了一下:

var count = []

for (var i = 0; i < markers.length; i++) {
count[markers[i].group] = count[markers[i].group] + 1 || 1 ;
}

输出这个结果:

count = [
candy: 1
foods: 3
fruits: 2
liquids: 2
]

我想在另一部分使用这个值,为此我需要将数组结构更改为如下所示:

count = [
{"item": "candy","qnt":1},
{"item": "foods","qnt":3},
{"item": "fruits","qnt":2},
{"item": "liquids","qnt":2}
]

我知道我可以做这样的事情:

var total_fruits = 0;
for (var i = 0; i < markers.length; i++) {
if (markers[i].group == "fruits"){
total_fruits++
}
}

但是想象一下,对于一组 50 多种类型,我需要多少个 if...

我将在 html 部分中使用与项目值相同的类的值,如下所示:

<ul>
<li class="candy">
<span class="qnt">1</span>
</li>
<li class="fruits">
<span class="qnt">2</span>
</li>
<li class="foods">
<span class="qnt">3</span>
</li>
<li class="liquids">
<span class="qnt">2</span>
</li>
</ul>

有什么建议或如何改进吗?

最佳答案

您可以使用reduce() 一步构建您想要的对象。这将构建一个键控到 group 的对象。要仅获取数组,请获取该对象的 Object.values():

var markers = [{"type":"Chocolate","name":"KitKat","group":"candy","icon":"candy","coords":[5246,8980],},{"type":"Fruit","name":"Orange","group":"fruits","icon":"fruis","coords":[9012,5493],},{"type":"Fruit","name":"Banana","group":"fruits","icon":"fruis","coords":[9012,5493],},{"type":"Food","name":"Rice","group":"foods","icon":"foods","coords":[6724,9556],},{"type":"Food","name":"Meat","group":"foods","icon":"foods","coords":[6724,9556],},{"type":"Food","name":"Beam","group":"foods","icon":"foods","coords":[6724,9556],},{"type":"Liquid","name":"Water","group":"liquids","icon":"liquids","coords":[6724,9556],},{"type":"Liquid","name":"Coffe","group":"liquids","icon":"liquids","coords":[6724,9556],},]

let counts = markers.reduce((obj, {group}) => {
if(!obj[group]) obj[group] = {"item": group, "qnt":1} // make a count item if it doesn't exist
else obj[group].qnt++ // or increment it
return obj
}, {})

console.log(Object.values(counts))

关于javascript - 计算每个值在数组中有多少个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53525181/

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