Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to empty an JS Object?

I have an object like

var person = {'id':null, 'name':'John Doe'}

After inserting the object value into the database, I will get another object from the server:

var personInDB = {'id':1234, 'name':'John Doe'}

I have used angular.merge to use updated the value of person with that of personInDB.

But, I want to empty person object before applying angular.merge, so that I only get the values in database. I don't want to assign new empty object to person as that will break data-binding in angular.

like image 990
Barun Avatar asked Sep 05 '16 05:09

Barun


People also ask

Can you create an empty object in JavaScript?

Can you create an empty object JavaScript? Objects can also be created using the new keyword. With the built-in Object Constructor in Javascript, new creates an empty object; or, this keyword can be used with a user-defined constructor function: with builtin Object Constructor .

How do you delete empty objects?

To remove empty objects from an array:filter() method to iterate over the array.. Pass each object to the Object. keys() method and check if the length of keys is not equal to 0 . The filter method will return a new array that doesn't contain empty objects.

Is delete bad in JS?

No, it's not considered bad practice.

Is Empty object JavaScript true?

The empty object is undefined, like this var empty_obj = {} . An undefined will be a false one.


2 Answers

I want to empty person object...I don't want to assign new empty object to person

I'm not aware of any kind of built-in object .deleteAllProperties() method, so that leaves looping through the properties and calling delete on each individually. Following is a reasonably tidy way to do that:

Object.keys(person).forEach(k => delete person[k])

Or the slightly longer non-ES6 arrow function version for support back as far as IE9:

Object.keys(person).forEach(function(k) { delete person[k]})

For even older IE just use a for..in loop (with a .hasOwnProperty() check).

And obviously you can put any of the above into a function for ease of re-use:

function emptyObject(obj) {
  Object.keys(obj).forEach(k => delete obj[k])
}

emptyObject(person)

Note that although this answers what you've asked, I'm not sure why you think you need to do it at all. The example you show in the question has the same two properties before and after, so angular.merge() would just overwrite the old values with the new values without any need to first empty the object. (Are you trying to allow for a case (not shown) where the old version of your object might have properties that no longer exist in the new version?)

like image 139
nnnnnn Avatar answered Sep 22 '22 11:09

nnnnnn


if you want empty the 'id' only

person['id']=null;

if you want to empty all attributes of the person object, then

Object.keys(person).forEach(key => person[key]=null);
like image 37
Karpak Avatar answered Sep 22 '22 11:09

Karpak