aWebDeveloper
aWebDeveloper

Reputation: 38332

Looping through object in JavaScript

if(properties != undefined)
{
    foreach(key in properties)
    {
        dialogProperty.key = property[key];
    }
    alert(dialogProperty.close);
}

How can I achieve/fix the above code? I think the above code is self explanatory.

Upvotes: 0

Views: 134

Answers (3)

Raynos
Raynos

Reputation: 169373

properties && Object.keys(properties).forEach(function(key) {
  dialogProperty[key] = properties[key];
});
console.log(dialogProperty.close);

The properties && check is to ensure that properties is not falsy.

The Object.keys call returns an array of all keys that the properties object has.

.forEach runs a function for each element in the array.

dialogProperty[key] = properties[key] set's the value of dialogProperty to be that of properties.

Upvotes: 2

lonesomeday
lonesomeday

Reputation: 237817

I think you mean for rather than foreach. You should also stop key being global and use Object.prototype.hasOwnProperty:

if(properties != undefined)
{
    for (var key in properties)
    {
        if (properties.hasOwnProperty(key) {
            dialogProperty[key] = properties[key]; // fixed this variable name too
        }
    }
    alert(dialogProperty.close);
}

NB Incorporated Kobi's fix too.

Upvotes: 4

Kobi
Kobi

Reputation: 137997

Assuming you're trying to copy all properties, you're probably looking for:

dialogProperty[key] = property[key];

dialogProperty.key is not dynamic, it sets the key property each time, the same way dialogProperty["key"] would.

Upvotes: 3

Related Questions