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



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

[
{"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)

除了上面的答案,我还想将数组转换为 2D 数组以进行迭代。 我站在@Kobe提供的代码的肩膀上来到这里. 我将发布此内容,它可以为未来的用户节省一些时间。

https://codepen.io/jsmartio/pen/gObMdvv

<script>
const data = [
{ id: 18, newsStory: 'Russia' },
{ id: 19, newsStory: 'Stormy' },
{ id: 20, newsStory: 'Russia' },
{ id: 21, newsStory: 'Collision' },
{ id: 22, newsStory: 'Stormy' },
{ id: 23, newsStory: 'James Harden' },
{ id: 24, newsStory: 'Stormy' },
{ id: 25, newsStory: 'Stephen A Smith' },
{ id: 26, newsStory: 'Collision' },
{ id: 27, newsStory: 'Stormy' },
{ id: 28, newsStory: 'Hunter' }
]
const init = () => {
// this will convert the object in to an array
var obj = data.reduce((a, {newsStory:s}) => (a[s] = (a[s] || 0) + 1, a), {})
document.getElementById('res1').innerHTML = '<pre>' + 
JSON.stringify(obj).replace(/,/g,",n") + '</pre>'
// this will convert at array into a 2d array (see output)
var countsArr = Object.keys(obj).map(i => { return [String(i), obj[i]]})
document.getElementById('res2').innerHTML = '<pre>' + 
JSON.stringify(countsArr).replace(/],/g,"],n") + '</pre>'
console.log(countsArr)
}
document.addEventListener('DOMContentLoaded', init);
</script>

@Kobe代码后的结果(步骤 1(

{
"Russia":2,
"Stormy":4,
"Colusion":2,
"James Harden":1,
"Stephen A Smith":1,
"Hunter":1
}

第二道工序后的最终二维阵列

[
["Russia",2],
["Stormy",4],
["Collision",2],
["James Harden",1],
["Stephen A Smith",1],
["Hunter",1]
]

最新更新