Home > Back-end >  Filtering array by string
Filtering array by string

Time:10-28

Can anybody please help me get this to work...

This snippet works

const acco = [{FullyQualifiedName=(-) Imposto Unico, Id=109, sparse=true, AcctNum=3.1.2.01.03027}, {FullyQualifiedName=13º Salário, Id=114, sparse=true, AcctNum=4.1.2.04.04062}, {Id=94, AcctNum=2.1.3.01.02183, FullyQualifiedName=13º Salário a Pagar, sparse=true}, {Id=90, FullyQualifiedName=Adiantamento de Férias, sparse=true}

var payacc = '2.1.3.01.02183';
var accDC = acco.filter(o => o.AcctNum === payacc);
if (accDC.length != 0) {
                var accvalid = accDC[0].AcctNum   ' '   accDC[0].FullyQualifiedName;
              }
//accvalid = 2.1.3.01.02183 13º Salário a Pagar

But this snippet below returns undefined

const acco = [{FullyQualifiedName=(-) Imposto Unico, Id=109, sparse=true, AcctNum=3.1.2.01.03027}, {FullyQualifiedName=13º Salário, Id=114, sparse=true, AcctNum=4.1.2.04.04062}, {Id=94, AcctNum=2.1.3.01.02183, FullyQualifiedName=13º Salário a Pagar, sparse=true}, {Id=90, FullyQualifiedName=Adiantamento de Férias, sparse=true}

var payacc = '02183';
var accDC = acco.filter(o => o.AcctNum.includes(payacc));
if (accDC.length != 0) {
                var accvalid = accDC[0].AcctNum   ' '   accDC[0].FullyQualifiedName;
              }

returns TypeError: Cannot read property 'includes' of undefined

I believe this happens cuz there is no AcctNum for the last register, but how do I skip this? Sorry if I'm missing something too obvious.

CodePudding user response:

Just check for o.AcctNum first in your filter function. That will solve your issue. I also fixed some other typos in your code.

const acco = [
  {FullyQualifiedName : "Imposto Unico", Id:109, sparse:true, AcctNum:"3.1.2.01.03027"},
  {FullyQualifiedName:"13º Salário", Id:114, sparse:true, AcctNum:"4.1.2.04.04062"},
  {Id:94, AcctNum:"2.1.3.01.02183", FullyQualifiedName:"a Pagar", sparse:true},
  {Id:90, FullyQualifiedName:"Adiantamento de Férias", sparse:true}]

var payacc = '2.1.3.01.02183';
var accDC = acco.filter(o => o.AcctNum && o.AcctNum === payacc);
if (accDC.length !== 0) {
                var accvalid = accDC[0].AcctNum   ' '   accDC[0].FullyQualifiedName;
                 console.log({accvalid})
              }
  • Related