如何清空JS对象? [英] How to empty an JS Object?

查看:249
本文介绍了如何清空JS对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似

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'}

我已经使用angular.merge来将person的值更新为personInDB的值.

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

但是,我想在应用angular.merge之前清空person对象,以便只获取数据库中的值.我不想为人分配新的空对象,因为那样会破坏角度数据绑定.

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.

推荐答案

我想清空person对象...我不想将新的空对象分配给person

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

我不知道任何种类的内置对象.deleteAllProperties()方法,因此在属性之间循环并在每个属性上分别调用delete.以下是一种合理而整洁的方法:

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

或者更长一点的非ES6箭头功能版本,甚至可以支持到IE9:

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]})

对于更老的IE,只需使用for..in循环(带有.hasOwnProperty()检查)即可.

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)

请注意,尽管这可以回答您的要求,但是我不确定您为什么认为自己需要这样做.问题中显示的示例之前和之后具有相同的两个属性,因此angular.merge()只需用新值覆盖旧值,而无需先清空对象. (您是否要考虑一种情况(未显示),其中对象的旧版本可能具有新版本中不再存在的属性?)

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

这篇关于如何清空JS对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆