0

The below format is fetching from server and its strangely adding null value in the last object. I want to remove null or undefined objecs from the array. Can anyone help me?

[
  {
    "addrSeq": "12",
    "addinfo": [
      {
        "virAddrSeq": "45"
      }
    ]
  },
  null
]
Spectric
  • 30,714
  • 6
  • 20
  • 43
vishnu
  • 4,377
  • 15
  • 52
  • 89
  • 3
    https://stackoverflow.com/a/38340730/3297914 You should check your API return though instead of cleaning the object afterwards. – Hirbod Oct 06 '21 at 02:17
  • 5
    Duplicate of [Remove blank attributes from an Object in Javascript](https://stackoverflow.com/questions/286141/remove-blank-attributes-from-an-object-in-javascript) – Samathingamajig Oct 06 '21 at 02:19

2 Answers2

3

You can use Array.filter to filter out null and undefined items by checking whether the item is not null (an undefined check is unnecessary, since null == undefined).

const arr=[{addrSeq:"12",addinfo:[{virAddrSeq:"45"}]},null,undefined];

const result = arr.filter(e => e != null)

console.log(result)
Spectric
  • 30,714
  • 6
  • 20
  • 43
3

let arr = [
  {
    "addrSeq": "12",
    "addinfo": [
      {
        "virAddrSeq": "45"
      }
    ]
  },
  null
];
arr = arr.filter((i)=>i !== null && typeof i !== 'undefined');
console.log(arr);
emptyhua
  • 6,634
  • 10
  • 11