Home > OS >  What is wrong with this counter (if-statement)? (Javascript)
What is wrong with this counter (if-statement)? (Javascript)

Time:03-11

I tried to loop threw an array in order to count the occurance of 'phone1'. The Data from the backend has the following structure:

[{
    Key: 'phone1',
    Recording: {
      ID: 'phone1',
      Tel: '1000',
      User: 'Maria',
      Price: '350',
      docType: 'asset'
    }]

My function for this looks like:

backendData.list[0].map((phone, i) => {
            var counter = 0;
             for (var i = 0; i < backendData.length; i  ) {
                if (backendData[i].Key === 'phone1') counter  ;
             }
             console.log(counter);
          });

The result I get is always 0, but it has to be 1 with my Data.

CodePudding user response:

Try this:

let counter = 0;
backendData.list[0].forEach((phone, i) => {
   if(phone.Key === 'phone1') counter  ;
   console.log(counter);
})

CodePudding user response:

You just can use Array.prototype.filter() to count objects by condition:

const backendData = [{Key:'phone1',Recording:{ID:'phone1',Tel:'1000',User:'Maria',Price:'350',docType:'asset'}}];

const result = backendData
  .filter(({ Key }) => Key === 'phone1')
  .length;

console.log(result);
.as-console-wrapper{min-height: 100%!important; top: 0}

  • Related