0
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.

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

or use Object.keys(properties).forEach
@Raynos If you assume ECMAScript 5, yes. I'm not 100% convinced the OP is at that stage...
3

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.

Comments

2
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.

1 Comment

Funny how different the browsers can be in their optimizations. jsperf.com/object-keys-vs-hasownproperty +1 for this approach, but I'd just clarify that Object.keys only returns enumerable keys, which of course would be desired here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.