如何将重复值对象计算为对象的值

时间:2019-01-18 16:45:52

标签: javascript arrays json object

如何计算new object个值中的对象值 可以说我有这样的json:

let data = [{
    no: 3,
    name: 'drink'
  },
  {
    no: 90,
    name: 'eat'
  },
  {
    no: 20,
    name: 'swim'
  }
];

如果我让用户在数组中未选择:[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循环

这里是the code I've attempted

let obj = [];
for (i of arr){
  for (j of data){
    let innerObj={};
    innerObj.num = i
    obj.push(innerObj)
  } 
}

3 个答案:

答案 0 :(得分:1)

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>

答案 1 :(得分:0)

也许是这样吗?您可以映射现有数据数组,并将过滤后的数组计数附加到每个数组对象。

let data = [
  {
    no: 3,
    name: 'drink'
  },
  {
    no:90,
    name: 'eat'
  },
  {
    no:20,
    name: 'swim'
  }
]

const test = [3,3,3,3,3,3,3,3,3,3,3,90,20,20,20,20]

const result = data.map((item) => {
  return {
    num: item.no,
    total: test.filter(i => i === item.no).length // filters number array and then checks length
  }
})

答案 2 :(得分:0)

You can check next approach using a single for/of loop. But first I have to create a Set with valid ids, so I can discard noise data from the test array:

const data = [
    {no: 3, name: 'drink'},
    {no: 90, name: 'eat'},
    {no: 20, name: 'swim'}
];

const userArr = [3,3,3,3,3,3,3,3,7,7,9,9,3,3,3,90,20,20,20,20];

let ids = new Set(data.map(x => x.no));
let newArr = [];

for (i of userArr)
{
   let found = newArr.findIndex(x => x.num === i)

   if (found >= 0)
       newArr[found].total += 1;
   else
       ids.has(i) && newArr.push({num: i, total: 1});
}

console.log(newArr);