What better way to check if an object is empty?

Asked

Viewed 179 times

2

I have the following object:

let obj = {};

If I try to validate obj.length return me a undefined, then I resorted to the Object.Keys alternative.. Object.keys(obj).length.. solved my problem.. but I wonder if there are any alternatives to this? some native javascript function.. sei la!

Thank you!

  • I don’t know if it helps you, but in CSS it has a native "function" for that, it calls :empty []s

  • In my case it is not possible to use CSS for this validation..

2 answers

6

You can create a function that will traverse the properties of the object and return the answer.
If the is precorra some property of the object, so it is not empty, it will return false. If he doesn’t go through the go, he will return true
There is an example of code below:

function objIsEmpty(obj) {
  for (let prop in obj) {return false}
  return true;
}

const obj = {'id': 1};
const obj2 = {};
const obj3 = new Object(); // obj vazio
const obj4 = {};
obj4.id = 2;
obj4.nome = 'Teste';

console.log(objIsEmpty(obj), obj);
console.log(objIsEmpty(obj2), obj2);
console.log(objIsEmpty(obj3), obj3);
console.log(objIsEmpty(obj4), obj4);

See if that suits you. Any questions, just talk.

-3

For this case, it can be checked in the same way as an attribute null.

 if(obj.length == null){
  ...código
 }

Or using the method: hasOwnProperty('Attribute'), where returns a boolean stating whether this property is null or not

obj = new Object(); 
obj.propUm = null;
obj.hasOwnProperty('propUm'); // retorna true
obj.propDois = undefined;
obj.hasOwnProperty('propDois'); // retorna true

If you really want to instantiate a null object, you should do it as follows:

obj = null

Because by creating obj = {}, you are instantiating an object (therefore no longer null)

  • Brother esse if if(obj.length == null) does not answer.. because the object even being empty or with attributes, will not be equal to null

  • And hasOwnProperty doesn’t answer either, because I don’t want to check if there’s a prop.. in obj, but if it’s empty or not..

  • Maybe you didn’t understand the question! =/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.