как посчитать повторяющиеся значения объекта, чтобы быть значением объекта - PullRequest
0 голосов
/ 18 января 2019

как посчитать стоимость объекта в 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 loop

Вот код, который я пытался :

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

Ответы [ 3 ]

0 голосов
/ 18 января 2019

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);
Lookup output

Основной выход

 
0 голосов
/ 18 января 2019

Вы можете проверить следующий подход, используя один цикл for/of. Но сначала я должен создать Set с действительными идентификаторами, чтобы я мог отбросить noise данные из массива test:

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);
0 голосов
/ 18 января 2019

Возможно, что-то подобное? Вы можете отобразить существующий массив данных и прикрепить отсчеты отфильтрованных массивов к каждому объекту массива.

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
  }
})
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...