javascript - check array inside an array length is empty then remove the parent array from the main array -


hi how check array inside array length empty remove parent array main array ,

think have array

[     {         "id": 71,         "campaignassets": [             {                 "id": 128             }         ]     },     {         "id": 99,         "campaignassets": []     } ] 

from above array id:71 have campaignassets array length 1 on other 1 "id": 99 dont have campaignassets have remove parent array means

    {         "id": 99,         "campaignassets": []     } 

so final array should

[     {         "id": 71,         "campaignassets": [             {                 "id": 128             }         ]     } ] 

this proposal features 2 solutions,

  1. generate new array , assign original array
  2. delete unwanted items without generating temporary.

1. new array

you filter array#filter

var data = [{ "id": 71, "campaignassets": [{ "id": 128 }] }, { "id": 99, "campaignassets": [] }];    data = data.filter(function (a) { return a.campaignassets.length; });    console.log(data);

in es6 it's shorter

var data = [{ "id": 71, "campaignassets": [{ "id": 128 }] }, { "id": 99, "campaignassets": [] }];    data = data.filter(a => a.campaignassets.length);    console.log(data);

2. without new array

for in situ solution, keeping array , delete elements 0 length, suggest use backward iteration , check length , use array#splice accordingly.

var data = [{ "id": 71, "campaignassets": [{ "id": 128 }] }, { "id": 99, "campaignassets": [] }],      = data.length;    while (i--) {      if (!data[i].campaignassets.length) {          data.splice(i, 1);      }  }    console.log(data);


Comments

Popular posts from this blog

sql - invalid in the select list because it is not contained in either an aggregate function -

Angularjs unit testing - ng-disabled not working when adding text to textarea -

How to start daemon on android by adb -