[Fixed] How to remove the undefined object from array using angular?

Issue

let myArr=[{
    "name": "",
    "columns": [
      {
        
        "data": "test1",
        "type": "",
        
        
      },
      undefined,
      {
        "data": "test1",
        "type": "",
      }
    ],
    "info": "value",
    
  }]

Above array of object having undefined or null values, I have to remove the undefined values.

Solution

This can be done by combining Array.map(), Object.keys(), Array.reduce(), Array.isArray() and Array.filter() (the core piece) as shown in the runnable code below:

let myArr=[{
    "name": "",
    "columns": [
      {        
        "data": "test1",
        "type": "",        
      },
      undefined,
      {
        "data": "test1",
        "type": "",
      }
    ],
    "info": "value",    
  }]
  
myArr = myArr.map(o => Object.keys(o).reduce((acc, key) => {
  let value = o[key];  
  if (Array.isArray(value)) {
    value = value.filter(o2 => o2);
  }
  acc[key] = value;
  return acc;
}, {}));

console.log(myArr);

Leave a Reply

(*) Required, Your email will not be published