首页 > 解决方案 > 如何将重复值对象计数为对象的值

问题描述

如何计算值中对象的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)
  } 
}

标签: javascriptarraysjsonobject

解决方案


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>


推荐阅读