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,
- generate new array , assign original array
- 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
Post a Comment