标签云

微信群

扫码加入我们

WeChat QR Code

我如何从一个JavaScript对象中删除一个属性吗?

Say I create an object as follows:

var myObject = {
    "ircEvent": "PRIVMSG",
    "method": "newURI",
    "regex": "^http://.*"
};

What is the best way to remove the property regex to end up with new myObject as follows?

var myObject = {
    "ircEvent": "PRIVMSG",
    "method": "newURI"
};


Find here a benchmark which compares "delete" vs "undefined" vs "null" jsben.ch/#/BWMiw

2018年05月23日40分19秒

developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

2018年05月23日40分19秒

Checked, it also works with "delete myJSONObject['regex'];" See: developer.mozilla.org/en/Core_JavaScript_1.5_Reference/…

2018年05月23日40分19秒

An upshot of one of the observations at the "understanding delete" link above, is that, since you cannot necessarily delete a variable, but only object properties, you therefore cannot delete an object property "by reference" -- var value=obj['prop']; delete value //doesn't work

2018年05月23日40分19秒

So it doesn't actually delete it? It just becomes undefined, but the key still exists? Am I missing something?

2018年05月23日40分19秒

Pete no, it does remove it. Given: var x = {a : 'A', b : 'B'}; Compare: delete x.a; typeof x.a; /* "undefined" */ x.hasOwnProperty('a'); /* false */ to x.b = undefined; typeof x.b; /* "undefined" */; x.hasOwnProperty('b'); /* true */

2018年05月23日40分19秒

ChristopherPfohl works for me. Like I said, it's actually quite in-depth, so it's a bit difficult to summarize. The basic response in the answer above is sufficient for almost all cases, the blog goes into some more of the edge cases and the reasons those cases exist.

2018年05月23日40分19秒

a property is assigned to undefined still is a property of an object, so it will not be removed by GC, unless misread your last paragraph.

2018年05月23日40分19秒

I was wrong to touch the theme of GC here. Both methods have the same result for GC: they remove the value linked to the key. If that value was the last reference to some other object, that object would be cleaned up.

2018年05月23日40分19秒

a property is assigned to undefined still is a property of an object, so it will not be removed by GC The GC doesn't manage anything about properties. It collects and removes values. As long as nothing references a value (an object, string, etc.) anymore, the GC does remove it from memory.

2018年05月23日40分19秒

BTW, that is the dual problem to check if a property exist on Javascript object. Using in operator is the reliable but slow. Check if the property is not undefined "is not the correct answer" but it is a way faster. check

2018年05月23日40分19秒

Is this answer still relevant? jsperf is currently down, but this benchmark seems to indicate that the speed difference is a mere 25%, which is nowhere close to the "~ 100 times slower" in this answer.

2018年05月23日40分19秒

Is there any way to delete multiple properties from same array using one expression

2018年05月23日40分19秒

warrior nope there is not

2018年05月23日40分19秒

When trying to delete multiple properties at once, would it not be better to just remap to a new object?

2018年05月23日40分19秒

This delete keyword, however, is much more convenient, lol

2018年05月23日40分19秒

This approach doesn't modify the original object which might be still referenced elsewhere. This might or might not be a problem depending on how it's used but it's something to keep in mind.

2018年05月23日40分19秒

B1KMusic Here's the way to delete an element from an Array: splice

2018年05月23日40分19秒

wulftone nope, that splits the array and does nothing to delete a value. I really think the best way to delete from an array where specific values are needed to be deleted is to use delete and make a Garbage Collection function to clean it up.

2018年05月23日40分19秒

I don’t see splice in your edit, but remove ought to be Array.prototype.remove = function(index) { this.splice(index, 1); };

2018年05月23日40分19秒

What's up with the downvotes?

2018年05月23日40分19秒

Maybe because the goal is to remove a property from an object, not to create a new one without the property... although, your solution is my favorite, as I prefer the immutable way.

2018年05月23日40分19秒

The question stated "to end up with new myObject".

2018年05月23日40分19秒

According to kangax.github.io/compat-table/esnext, object rest properties aren't finalized for ES6, have zero browser implementations, and only Babel provides support.

2018年05月23日40分19秒

This is actually a sweet one-liner for new object assignment without unwanted props, and already supported with Node.js 8.*/9.* with --harmony: node.green/…

2018年05月23日40分19秒

Keep in mind that if your object's keys are numbers, you may need to _.omit(collection, key.toString())

2018年05月23日40分19秒

Why did you link to Wikipedia, and not to underscorejs.org?

2018年05月23日40分19秒

E730 Good question. I don't know why one of the editors changed it to point to wikipedia.org/wiki/Underscore.js. I changed it back to underscorejs.org.

2018年05月23日40分19秒

Hmmmmm.... Underscore is ~100x slower than delete obj[prop] which is ~100x slower than obj[prop] = undefined.

2018年05月23日40分19秒

You're wrong - only objects are passed by reference in JavaScript, so if myJSONObject.regex's value is a string and you assign it to some other object, the other object has a copy of this value.

2018年05月23日40分19秒

You are right and this is a quote: "to be careful about your other references to the same object."

2018年05月23日40分19秒

Gothdo it has more benefits, especially when you need to do some functional stuff. E.g. you can assign function to variable, pass as an argument or use apply, call, bind functions...

2018年05月23日40分19秒

I would think you should always use splice on an array instead of delete.

2018年05月23日40分19秒

JoelTrauger : That's what I'm saying ;-)

2018年05月23日40分19秒

Yes. My comment is that that delete shouldn't even be a thing. It's splice is what the OP was looking for.

2018年05月23日40分19秒

JoelTrauger : As I tried to explain, delete should be used for object properties and splice for array elements.

2018年05月23日40分19秒

Splice is really slow. While it should be used instead of delete on arrays, it would be wisest to not create code centered around it at all.

2018年05月23日40分19秒

It might be worth noting that even though using the delete operator is healthy in regard of garbage collection, it can be unexpectedly slow, in no small part for the same reason.

2018年05月23日40分19秒

delete foo.bar works even if bar doesn't exist, so your test is a bit too much, IMHO.

2018年05月23日40分19秒

PhiLho that depends on where you are running JavaScript. In Node.js I believe this causes your server to crash.

2018年05月23日40分19秒

delete foo.bar; only throws an exception if foo is falsy, or if you're in strict mode and foo is an object with an unconfigurable bar property.

2018年05月23日40分19秒

I don't remember the exact issue I've had with this but I think the problem may appear when foo itself doesn't exist and you try to delete it's property.

2018年05月23日40分19秒

Yes, you have to test if foo exists, otherwise foo.bar will throw an exception, but you don't need to check the existence for bar before deleting it. That's the "too much" part of my comment. :-)

2018年05月23日40分19秒

This function works like a charm, but why do we need return true and return false? My version of the code: codepen.io/anon/pen/rwbppY. Will my version fail for any case?

2018年05月23日40分19秒

witty2017 it won't fail. The place where I used the function also needed to check whether the property already exists or not. if the property doesn't exist, it'll return false. If it finds the property and deletes it, it'll return true.

2018年05月23日40分19秒

Also JSON.parse(JSON.stringify({ ...myObject, regex: undefined }))

2018年05月23日40分19秒

SyntaxError: Unexpected token '...'. Expected a property name.?

2018年05月23日40分19秒

Try it with a modern browser such as Firefox, Chromium or Safari. And I expect it to work with Edge as well.

2018年05月23日40分19秒

As an alternative, if your customers force you to support outdated browsers, you could consider using TypeScript which transpiles your code into legacy syntax (+ gives you the benefit of static type safety).

2018年05月23日40分19秒

github.com/gildata/RAIO/issues/164

2018年05月23日40分19秒