简体   繁体   English

Javascript从属性中删除对象

[英]Javascript remove object from property

If you have an object attached to a property like so :如果您有一个对象附加到这样的属性:

obj = {};
obj.prop = {name:'test'};

Is there a way, similar to using array.splice , to remove the object from that property, and return it so it can be attached to another object?有没有一种方法,类似于使用array.splice ,从该属性中删除对象,并返回它以便它可以附加到另一个对象?

Sure you can:你当然可以:

 var obj = {}; obj.prop = { name: 'test' }; var newObj = { prop: obj.prop} ; // Copy prop to a new object delete obj.prop; // delete `prop` on the old object. document.body.textContent = 'newObj: ' + JSON.stringify(newObj);

delete throws an error in strict mode if the property is an own non-configurable property (returns false in non-strict).如果属性是自己的不可配置属性,则delete在严格模式下抛出错误(在非严格模式下返回 false)。 It returns true in all other cases.在所有其他情况下它返回true

So, while there technically isn't a function like pop or splice that returns the removed property, it's trivial to work around that.因此,虽然技术上没有像popsplice这样的函数返回已删除的属性,但解决这个问题很简单。

To delete/return a property from an object in one swoop, I think you need your own function for this.要一次性从对象中删除/返回属性,我认为您需要自己的函数。 Something like:就像是:

 function removeValue(obj, property) { var prop = obj[property]; delete obj[property]; return prop; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM