javascript - 如何将重复值对象计数为对象的值
问题描述
如何计算值中对象的new object
值可以说我有这样的json:
let data = [{
no: 3,
name: 'drink'
},
{
no: 90,
name: 'eat'
},
{
no: 20,
name: 'swim'
}
];
如果我让用户在数组中选择 no:[3,3,3,3,3,3,3,3,3,3,3,90,20,20,20,20]
所以输出应该是一个数组
[
{
num: 3,
total: 11
},
{
num: 90,
total: 1
},
{
num:20,
total: 4
}
];
我想知道如何用for/of
循环来做到这一点
这是我尝试过的代码:
let obj = [];
for (i of arr){
for (j of data){
let innerObj={};
innerObj.num = i
obj.push(innerObj)
}
}
解决方案
const data = [{"no":3,"name":"drink"},{"no":90,"name":"eat"},{"no":20,"name":"swim"}];
const arr = [3,3,3,3,3,3,3,3,3,3,3,20,20,20,20,80,80];
const lookup = {};
// Loop over the duplicate array and create an
// object that contains the totals
for (let el of arr) {
// If the key doesn't exist set it to zero,
// otherwise add 1 to it
lookup[el] = (lookup[el] || 0) + 1;
}
const out = [];
// Then loop over the data updating the objects
// with the totals found in the lookup object
for (let obj of data) {
lookup[obj.no] && out.push({
no: obj.no,
total: lookup[obj.no]
});
}
document.querySelector('#lookup').textContent = JSON.stringify(lookup, null, 2);
document.querySelector('#out').textContent = JSON.stringify(out, null, 2);
<h3>Lookup output</h3>
<pre id="lookup"></pre>
<h3>Main output</h3>
<pre id="out"></pre>
推荐阅读
- python - scrapy python CrawlSpider不爬行
- php - 来自通过 php 加载的 xml 的缓存值
- sql-server - 如何通过 alter table 启用增量统计
- python - 在 gremlin-python 中使用合并和值之间的组合失败
- android - 一个一个地显示文本
- visual-studio-code - 需要帮助在 Visual Studio Code 中安装扩展
- typescript - 如何检查数组是否不包含 Ionic 4 上的另一个数组?
- javascript - 是否有可能在一个阶段获得所有字符的句柄?
- winston - 如何防止高级消息登录到winston中的所有低级消息?
- java - Springboot application.properites 未读取