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?)