0

I have object with bad indexes. I can't edit this, because i application this working ok.

var object = { "aaa": 1, "aaa": 2, "aaa" : 3, "aaa" : 4};
$.each(object, function(key, value){

});

how can i remove all values where value = 2 and 4?

Tom Mesgert
  • 1,301
  • 2
  • 10
  • 6

5 Answers5

4

You can't. Every value overwrites the previous one in the literal.

$> ({ "aaa": 1, "aaa": 2, "aaa" : 3, "aaa" : 4});
Object
    aaa : 4
$>

You will have to ensure that the object literal is well-formed, then use something like this (ES5) :

var filteredObject = Object.keys( yourObject ).reduce( function ( target, key ) {
    if ( yourObject[ key ] !== 2 && yourObject[ key ] !== 4 )
        target[ key ] = yourObject[ key ];
    return target;
}, { } );
Maël Nison
  • 7,055
  • 7
  • 46
  • 77
  • Nison is correct, your object will always be `Object { aaa=4 }`. See this fiddle to demonstrate the result. http://jsfiddle.net/SUpwM/ `console.log(object);` will show you the object. – Nope Aug 07 '12 at 13:37
  • Technically this is a well-formed object literal [as per ECMAScript 3](http://interglacial.com/javascript_spec/a-11.html#a-11.1.5). – Tgr Aug 07 '12 at 13:42
1

Can't you simply do an if(value!=2 && value!=4) into the for?

Lord Spectre
  • 761
  • 1
  • 6
  • 21
  • Create a new empty object and add the elements from the first to the second only if they match your condition. The $.filter instead is for an array of JQuery objects. – Lord Spectre Aug 07 '12 at 13:31
1

You can try the delete keyword to remove the key and that will remove the value

Here is the code

var object = { "a": 1, "b": 2, "c" : 3, "d" : 4};
$.each(object, function(key, value){
   if(value==2 || value==4){
         delete object[key];
   }
});

Note : I assumed that the same keys in your example is an error.

Clyde Lobo
  • 9,126
  • 7
  • 34
  • 61
1

To remove all values where value == 4:

for (var member in object) { if (object[member]==4) {delete object[member]} }
Holger Brandt
  • 4,324
  • 1
  • 20
  • 35
nuno
  • 194
  • 1
  • 11
0

I think you would want to use filter instead of each.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445