PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 28, 2022

[FIXED] How to determine if a variable is an empty object, empty array or empty string?

 October 28, 2022     is-empty, javascript     No comments   

Issue

I have an object whose keys can have have values which can be object, string or array.

const obj = {
  key1: 'asdf',
  key2: {},
  key3: ['a','b','c'],
  key4: [],
  key5: '',
}

I have to filter all the keys which are empty i.e empty objects, empty array or empty string.

Is there any other way than writing conditions based on typeof of keys and then checking null ?


Solution

Simply use Object.keys()

if (Object.keys(something).length) console.log("Not empty");

This works for all of strings, arrays, and of course, objects.

You can check the Object.keys documentation for more details, specifically, the examples section and the non-object coercion section, which state:

// simple array const arr = ['a', 'b', 'c'];
console.log(Object.keys(arr)); // console: ['0', '1', '2']

// array-like object const obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.keys(obj)); // console: ['0', '1', '2']

and

In ES5, if the argument to this method is not an object (a primitive), then it will cause a TypeError.

From ES2015 onwards, a non-object argument will be coerced to an object.

// In ES5 Object.keys('foo');  // TypeError: "foo" is not an object

// In ES2015+ Object.keys('foo');  // ["0", "1", "2"]


Answered By - mmdts
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing