-2

I have an object like this:

var names = { 45: "Jeff", 145: "Peter", 11: "Dandie", 879: "Michael" }

How do I remove "Peter" from the object?

Felix Kling
  • 756,363
  • 169
  • 1,062
  • 1,111
Mansa
  • 2,147
  • 8
  • 33
  • 64

2 Answers2

0

try this

delete names['145'];

or

delete names.145;
Amit
  • 15,021
  • 8
  • 44
  • 66
-1

The code is bad practice, the keys and values are in the wrong order. Try the following to achieve what you want:

for(var key of Object.keys(names))
    if(names[key]=='John')
         delete names[key];

Without for .. of:

Object.keys(names).forEach(function(key){
    if(names[key]=='John')
         delete names[keys];
});
simonzack
  • 17,855
  • 12
  • 65
  • 107
  • 1
    `for...of` doesn't exist in most implementations yet. If you have an array, use a normal `for` loop. – Felix Kling Jul 21 '13 at 16:24
  • How is that a reason to downvote my answer. This isn't an array, it's an Object – simonzack Jul 21 '13 at 16:25
  • I don't know why someone downvoted your answer (how can I?). But I can understand the downvote. Personally I'd find an answer that doesn't work in 99% for all environments "not useful". – Felix Kling Jul 21 '13 at 16:26
  • I've added an alternative. btw, 99% of all environments include ie 6. – simonzack Jul 21 '13 at 16:29
  • Well, you must agree that using a feature which is not implemented in any browser yet is not really helpful. On the other hand, a solution that works in all browser but IE6 is useful. – Felix Kling Jul 21 '13 at 16:42
  • It has been implemented in firefox for a long time. But I agree with you on IE6. – simonzack Jul 21 '13 at 16:46