Search code examples
javascriptarraysnamedtyped

Transverse object array and replace the value of all fields in JavaScript


quick question (and maybe easy) for y'all:

I got this array:

this.skins = {
    "hologramDark": {
        dialog: {
            default: "bgDialog"
        },
        button: {
            default: "btnDefault",
            disabled: "btnDisabled",
            focused: "btnFocused",
            pushed: "btnPushed",
        }
    }
};

And I need to (coming from C#+LINQ world) do a "for each item in "hologramDark", replace dialog "default:"'s value with the result of a function (for example, assignImage(dialog.default)), then for each buttons's values (default, disabled, focused, etc) do the same thing.

Any pointers? I've worked with normal arrays [] but I don't know how to transverse these ones.

Thanks!


Solution

  • You can loop over properties of an Object using for..in

    var obj = this.skins.hologramDark, key; // remember to var
    for (key in obj) { // loop over each key
        if (obj.hasOwnProperty(key)) { // if the key is on the obj (not inherited)
            if (typeof obj[key] === 'object') { // and the property is another object
                obj[key].default = 'foo'; // set the property default
            }
        }
    }