Languages

JavaScript - How to remove empty object from array?

0 points
Asked by:
May87
827

I have an array of objects and I want to remove empty objects from it:

const array = [{ id: 1 }, {}, {}, {}];

How can I do this?

1 answer
0 points
Answered by:
May87
827

Use filter() method with Object.keys() to find and remove all objects that doesn't contain any key.

Practical example:

// ONLINE-RUNNER:browser;

const array = [{ id: 1 }, {}, {}, {}];

const result = array.filter((value) => Object.keys(value).length !== 0);

console.log(JSON.stringify(result)); // [ { id: 1 } ]

 

References

  1. Array.prototype.filter() - JavaScript | MDN
  2. Object.keys() - JavaScript | MDN
0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join