gpt4 book ai didi

Javascript 计算分配给对象属性的唯一值总数

转载 作者:行者123 更新时间:2023-11-30 10:57:49 26 4
gpt4 key购买 nike

我的数据库查询返回一个对象数组,如下所示:

[
{"id":18,"newStory":"Stormy"},
{"id":19,"newStory":"Russia"},
{"id":20,"newStory":"Stormy"},
{"id":21,"newStory":"Witch Hunt"},
{"id":22,"newStory":"Stormy"},
{"id":23,"newStory":"Russia"}
]

我需要每个独特的 newStory 的故事总数。然后,我想遍历这些总数,生成类似于以下数组的内容:

newStoryTotal["Stormy"][2]
newStoryTotal["Witch Hunt"][1]
newStoryTotal["Russia"][3]

我曾尝试使用 reduce 和 lodash,但我缺乏这方面的专业知识。我也知道这可以使用嵌套的数据库查询来完成,但我试图通过单个查询 + Javascript 进行计数来完成。

最佳答案

你可以使用一个简单的reduce:

const data = [
{ id: 18, newStory: 'Stormy' },
{ id: 19, newStory: 'Russia' },
{ id: 20, newStory: 'Stormy' },
{ id: 21, newStory: 'Witch Hunt' },
{ id: 22, newStory: 'Stormy' },
{ id: 23, newStory: 'Russia' }
]

const output = data.reduce((a, {newStory:s}) => (a[s] = (a[s] || 0) + 1, a), {})
console.log(output)

当然,如果您很难阅读一行,您可以随时将其写出来以提高可读性:

const data = [
{ id: 18, newStory: 'Stormy' },
{ id: 19, newStory: 'Russia' },
{ id: 20, newStory: 'Stormy' },
{ id: 21, newStory: 'Witch Hunt' },
{ id: 22, newStory: 'Stormy' },
{ id: 23, newStory: 'Russia' }
]

const output = data.reduce((accumulator, object) => {
if (accumulator[object.newStory] !== undefined) {
accumulator[object.newStory]++
} else {
accumulator[object.newStory] = 1
}
return accumulator
}, {})
console.log(output)

关于Javascript 计算分配给对象属性的唯一值总数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59307776/

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