harmonius cool
harmonius cool

Reputation: 347

Removing an empty array from an object with JavaScript

I have this JSON object myFilters:

{"filters":
      {"role":"","jobs":[]}
}

I can correctly remove the empty object from it with this function clean (myFilters):

function clean(obj) {
  for (var propName in obj) {
    if (
      obj[propName] === null ||
      obj[propName] === undefined ||
      obj[propName] === ""
    ) {
      delete obj[propName];
    }
  }

So now, my myFilters object becomes:

{"filters":
    { "jobs":[] }
}

How can I now remove the empty array and the key from my JSON object?

Upvotes: 0

Views: 110

Answers (6)

Rohìt Jíndal
Rohìt Jíndal

Reputation: 27192

Try this :

var filterObj = {
	"filters": {
		"role": "",
		"jobs": []
	}
};

for (var i in filterObj) {
  for (var j in filterObj[i]) {
  	if ((filterObj[i][j] === null) ||
        (filterObj[i][j] === undefined) ||
        (filterObj[i][j].length === 0)) {
        delete filterObj[i][j];
    }
  }
}

console.log(filterObj);

Upvotes: 1

norbitrial
norbitrial

Reputation: 15166

I like Saveli Tomac's solution, so I upvoted that. Let me show you an additional shortening on the original solution also.

As it's been stated that you need to check 2 more things if you are looking for an empty array. So what about checking null, undefined and '' values easier?

if (!undefined) { console.log('undefined needs to be deleted') };
if (!null) { console.log('null needs to be deleted') };
if (!'') { console.log(`'' needs to be deleted`) };

Checking Array.length if it has 0 value can be also shorter just like the following:

const array1 = [];
const array2 = [1,2,3];
if (!array1.length) { console.log('array1 has 0 length') };
if (!array2.length) { console.log('array2 has 0 length') };

So based on those code snippets you can have an additional shortening just like the following:

// extended with other types for the demo
let myObject = { "filters": { "role": "", "jobs": [], "nullValue": null, "undefinedIsHere": undefined, "arrayWithValue": [1,2,3], "stringValue": "hello", "numberishere": 123 } };

const clean = (obj) => {
  for (let propName in obj) {
    if (
      !obj[propName] ||
      Array.isArray(obj[propName]) && !obj[propName].length
    ) { delete obj[propName] };
  }
}

clean(myObject.filters);
console.log(myObject);

Or with a 1️⃣ liner:

// extended with other types for the demo
let myObject = { "filters": { "role": "", "jobs": [], "nullValue": null, "undefinedIsHere": undefined, "arrayWithValue": [1,2,3], "stringValue": "hello", "numberishere": 123 } };

const clean = (obj) => {
  Object.keys(obj).forEach(propName => (!obj[propName] || Array.isArray(obj[propName]) && !obj[propName].length) && delete obj[propName]);
}

clean(myObject.filters);
console.log(myObject);

Read further here:

  1. Array.isArray()
  2. Array.length

I hope this helps!

Upvotes: 1

ylmz
ylmz

Reputation: 46

It should be like this:

function clean(obj) {
  for (var propName in obj) {
    if (obj.hasOwnProperty(propName) && 
      obj[propName] === null ||
      obj[propName] === undefined ||
      obj[propName] === "" || 
      (Array.isArray(obj[propName]) && obj[propName].length <= 0)
    ) {
      delete obj[propName];
    }
  }
}

Upvotes: 0

Umair Sarfraz
Umair Sarfraz

Reputation: 5953

Saveli's answer should work fine. Here's an alternative approach you can use to achieve the same result.

const object = {
  "filters": {
    "role": "",
    "jobs": [],
    "foo": undefined,
    "baz": null,
    "bar": {},
    "moreJobs": ['1', '2']
  }
}

const result = {
  filters: Object.keys(object.filters).reduce((acc, key) => {
    if (
      object.filters[key] !== null &&
      object.filters[key] !== undefined &&
      object.filters[key] !== '' &&
      typeof object.filters[key] === 'object' && Object.keys(object.filters[key]).length > 0
    ) {
      acc[key] = object.filters[key];
    }

    return acc;
  }, {})
};

console.log(result);

Upvotes: 0

Hamid Javadi
Hamid Javadi

Reputation: 211

You should check the type of property before check its value by the typeof

The jobs property is an object and you can check its value by its length. it is empty if its length equals to 0.

function clean(obj) {

    for (var propName in obj) {

        if (typeof (obj[propName]) == 'object') {

            if (obj[propName].length == 0) {
                delete obj[propName];
            }

        } else {

            if (
                obj[propName] === null ||
                obj[propName] === undefined ||
                obj[propName] === ""
            ) {
                delete obj[propName];
            }

        }
        
    }

}

Upvotes: 1

svltmccc
svltmccc

Reputation: 1386

You should add one more condition like

function clean(obj) {
  for (var propName in obj) {
    if (
      obj[propName] === null ||
      obj[propName] === undefined ||
      obj[propName] === "" ||
      Array.isArray(obj[propName]) && obj[propName].length === 0
    ) {
      delete obj[propName];
    }
  }
}

Upvotes: 1

Related Questions