简体   繁体   中英

Remove empty object from array of objects

I have an array of objects and a delete function that pass the index as a parameter but fails to remove the empty object. Objects containing properties can be removed. Does anyone know how to fix it? The example code is shown below.

let array = [
{
  id: '1',
  name: 'sam',
  dateOfBirth: '1998-01-01'
},
{
  id: '2',
  name: 'chris',
  dateOfBirth: '1970-01-01'
},
{
  id: '3',
  name: 'daisy',
  dateOfBirth: '2000-01-01'
},
{}
]

// Objects contain properties can be removed but empty object can not be removed.
const deleteItem = (index) => {
  return array.splice(index, 1);
};

Use Array.filter to filter out the items which have no properties

 let array = [ {id:"1",name:"sam",dateOfBirth:"1998-01-01"}, {id:"2",name:"chris",dateOfBirth:"1970-01-01"}, {id:"3",name:"daisy",dateOfBirth:"2000-01-01"}, {} ] const filtered = array.filter(e => Object.keys(e).length) console.log(filtered)

The above works since Object.keys will return an array of the properties of the object. Getting its length property will get the number of items in the array. If the length property is 0 , it is coerced to false (see: Falsy values ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM