Search code examples
javascriptrestfetchkey

Javascript fetch group total results by key


I'm performing a javascript fetch where I'm returning a json from a GET response and I'd need to group by the total amount of occurrences for each category (my keys). Here's an example of my json:

[{Id, Var1, Var2, CreationDate},
{1, 123, abc123, 2020-12-11},
{2, 1234, abc123, 2020-12-12},
{3, 12345, abc123, 2020-12-12},
{4, 1234, abc123, 2020-12-13},
{5, 321, cda123, 2020-12-15},
{6, 3214, cda123, 2020-12-15},
{7, 5432, fff123, 2020-12-16},
{8, 5432, fff123, 2020-12-16},
{9, 5432, fff123, 2020-12-16},
{10, 5432, fff123, 2020-12-16},
{11, 5432, ddd123, 2020-12-16},
{12, 5432, ddd123, 2020-12-16},
{13, 5432, ddd123, 2020-12-16},]

I'd like to group by the returning result by key, where key is "Var2" and it is part of the values I have in the array. To match it just need to contains one of the values in the listOfVariables array. here's my code:

var myObj;
var result;
var listOfVariables = [abc, cda, fff, ddd];
fetch('https://blashblashblash.com?listOfVariables')
.then(res=>res.json())
.then(data=>myObj= data)
.then(() =>
    myObj.forEach(function (elem){
        var variable = elem.Var2.includes(listOfVariables);
        if (result[variable ]) {
                result[variable ] += 1;
            } else {
                result[variable ] = 1;
            }
    });
    listOfVariables.forEach(variable => {
            if(!result.hasOwnProperty(variable )) {
                finalResult[variable ] = 0;
            } else {
                finalResult[variable ] = result[variable ];
            }
    });

the final result I get is:

[abc: 0
 cda: 0,
 fff: 0,
 ddd, 0]

but it should be:

[abc: 4,
cda: 2,
fff: 4,
ddd: 3]

where am I wrong? Apparently my code can't understand if the variables contains, as a substring, one of the elements of the array lisrOfVariables. Thank you


Solution

  • const result = [];
    const finalResult = [];
    const listOfVariables = ['abc', 'cda', 'fff', 'ddd'];
    
    fetch('https://blashblashblash.com?listOfVariables')
      .then(res => res.json())
      .then((data) => data.forEach((elem) => {
        const variable = elem.Var2;
        const variableInList = listOfVariables.includes(variable);
    
        if (variableInList) {
          result[variable] = (result[variable] || 0) + 1;
        }
      }));
    
    listOfVariables.forEach(variable => {
      finalResult[variable] = result.hasOwnProperty(variable) ? result[variable] : 0;
    });