Home > Software design >  Remove empty object from array of objects
Remove empty object from array of objects

Time:11-10

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);
};

CodePudding user response:

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)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Try this one. here 'newArray' will provide the array object which are not empty.

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Arrays</h2>

<p id="demo"></p>

<script>
debugger;
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'
},
{}
]
var newArray = array.filter(val => Object.keys(val).length !== 0);

</script>

</body>
</html>
  • Related