dwaddell
dwaddell

Reputation: 1506

What's the best way to add an additional property for each property in an object in IE8

First off I want to say I know there are easy ways around this issue but just by googleing and looking on stackoverflow it doesn't seem like there is a set way you are suppose to go about doing this so I wanted to see if anyone out there had ran into this before and came out with a nice solution. Here is my issue, I want to add an additional property for each property in an object. This works fine in newer IEs and in Firefox but will cause an infinite loop in IE8.

var oObject = { One : '1', Two : '2' };

for ( var key in oObject ) // Loops twice in IE10 and FF, loops infinitely in IE8
{
  console.log(oObject[key]);
  oObject[key+'_additionalProperty'] = 'Test';
}

Is there a way to do this without having to create a variable that holds the original value of oObject just to add an additional property for each property in oObject?

Note: For those jQuery fans out there $.each has the same issue. Also, I wish I could just not support IE8.

UPDATE:

JSFIDDLE: http://jsfiddle.net/dwaddell/rH89K/

Additional information: I actually haven't tested this in a true IE browser, I have been using the Developer Tools from IE10 and selecting IE8 for Browser Mode and IE 8 standards for Document Mode. This may make some kind of difference, I am not sure.

Upvotes: 3

Views: 159

Answers (2)

canon
canon

Reputation: 41715

Apparently, IE8 doesn't cache the properties list when using for...in. So, you continually add keys... adding additional properties for your additional properties and so on.

At any rate, a safeguard is to get your keys first like so (fiddle):

var oObject = {
  One: '1',
  Two: '2'
};

var keys = []; // plain array for caching our keys

// add keys to our cache
for (var key in oObject) {
  keys.push(key);
}

// loop through the cached keys and add new properties to oObject
for (var i = 0, ln = keys.length; i < ln; i++) {
  oObject[keys[i] + "_additionalProperty"] = "test";
}

console.log(oObject);

Upvotes: 2

Pheonix
Pheonix

Reputation: 6052

var oObject = { One : '1', Two : '2' };
var keys = Object.keys(oObject);
for ( var i=0;i<keys.length;i++) // Loops twice in IE10 and FF, loops infinitely in IE8
{
  oObeject[keys[i]+'_additionalProperty'] = 'Test';
}

Edit:

Your code should work as it is:

http://msdn.microsoft.com/en-us/library/ie/gg622937(v=vs.85).aspx

Edit 2:

An implementation of Object.Keys for ie8

Object.keys = Object.keys || function(o) {  
    var result = [];  
    for(var name in o) {  
        if (o.hasOwnProperty(name))  
          result.push(name);  
    }  
    return result;  
};

http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation

Upvotes: 1

Related Questions