user91579631 user91579631 - 17 days ago 6
JSON Question

Remove objects from this array of object when certain criteria is met

I have this array of object in javascript.

var array = [ { DATA_ID: 1,
DATA_NAME: 'XX',
DATA_GROUP: 2313,
CODE_NO: 1 },
{ DATA_ID: 6,
DATA_NAME: 'YY',
DATA_GROUP: 4213,
CODE_NO: 2 },
{ DATA_ID: 4,
DATA_NAME: 'ZZ',
DATA_GROUP: 2123,
CODE_NO: 3 },
{ DATA_ID: 8,
DATA_NAME: 'ZZ',
DATA_GROUP: 2123,
CODE_NO: 3 } ]


I want to remove objects from the array of objects when the property CODE_NO === 3.

The result will look like this;

[ { DATA_ID: 1,
DATA_NAME: 'XX',
DATA_GROUP: 2313,
CODE_NO: 1 },
{ DATA_ID: 6,
DATA_NAME: 'YY',
DATA_GROUP: 4213,
CODE_NO: 2 }
]


I am using node.js v6

Answer

This code will work. The trick lies in using array.splice(i,1) to remove the object in question.

for (let i=0;i< array.length; i++  ){
      if (array[key].CODE_NO===3){            
        array.splice(i,1);
      }
   }

array is the array posted in your question.

Comments