标签云

微信群

扫码加入我们

WeChat QR Code

我如何从一个JavaScript对象中删除一个关键?[重复]

This question already has an answer here:

Let's say we have an object with this format:

var thisIsObject= {
   'Cow' : 'Moo',
   'Cat' : 'Meow',
   'Dog' : 'Bark'
};

I wanted to do a function that removes by key:

removeFromObjectByKey('Cow');


Do you want the function to be a jQuery function or what does this have to do with jQuery?

2018年05月28日33分12秒

That is actually a JavaScript object, associative arrays do not exist in JavaScript.

2018年05月28日33分12秒

Yeah just some confusion with terminology I think, ie it's Javascript not Jquery, and it's an object not array (OP may come from other languages with associative arrays).

2018年05月27日33分12秒

If you are looping over keys in an object, and delete them if they match a certain value, does this affect the key index while you are looping over it?

2018年05月28日33分12秒

It seems to me that running through that object with for (var key in object) will still match that key and trying to use object[key] in the loop will throw an error. (or return undefined)

2018年05月27日33分12秒

Beware that IE8 may throw an exception when using delete in certain circumstances. See stackoverflow.com/questions/1073414/…

2018年05月27日33分12秒

except it leaves an undefined in the array which makes it difficult to iterate.

2018年05月27日33分12秒

Does anyone know the runtime of this operation?

2018年05月27日33分12秒

Downvoted. The thing is that both in underscore and lodash _.omit returns new object, does not modify the current one. So, this is slightly a different thing.

2018年05月27日33分12秒

shabunc The same with pure javascript. delete o.properrty does a lot more harm than good behind the scenes, as it changes o‘s hidden class and makes it a generic slow object.

2018年05月27日33分12秒

object.property = undefined is legit. Worked perfectly! (upvoted)

2018年05月27日33分12秒

Thanks mate, neat solution.

2018年05月27日33分12秒

Upvoted. A new immutable object is preferable in many cases.

2018年05月27日33分12秒