Michel Müller
Michel Müller

Reputation: 5705

"for var in" accessing JS object returns everything *but* own properties?

I'm at a loss here. Can anyone explain how the following console output is possible? Why is label_multilanguage_keynot showing up when iterating with for var p in?

    > Object.getOwnPropertyNames(design_element)
    (6) ["label_multilanguage_key", "value", "display_priority", "name", "help_text", "hidden"]

    > for (var p in design_element) console.log(p);
    VM226:1 value_type
    VM226:1 element_type
    VM226:1 requirement_setting
    VM226:1 multiple_values_setting
    VM226:1 user_enabled_setting
    VM226:1 grid_size_setting
    VM226:1 show_to_users
    VM226:1 disable_label
    undefined

    > console.log(design_element)
    VM262:1 
    {label_multilanguage_key: "&&mlkey_enable_filtering_for_id", value: false, display_priority: 6, name: "enable_filtering_for_id", help_text: "&&mlkey_proto_enable_filtering_help_text", …}
    display_priority: 6
    help_text: "&&mlkey_proto_enable_filtering_help_text"
    hidden: true
    label_multilanguage_key: "&&mlkey_enable_filtering_for_id"
    name: "enable_filtering_for_id"
    value: false
    __proto__: Object

    typeof(design_element)
    "object"

Re: The question of how these objects are created - it will take a while longer to confirm, but it should be created using a call like

Object.create(element_structure.StaticTextField,{label_multilanguage_key:{value:ML_KEYS.first_name},name:{value:"first_name"}})

If that's the case, is a non-enumerable behavior possible? Or was there obviously a screw-up in the object initialization?

Upvotes: 0

Views: 44

Answers (2)

Bergi
Bergi

Reputation: 664620

Was there obviously a screw-up in the object initialization?

Yes, using Object.create with property descriptors (like Object.defineProperties) creates non-enumerable properties by default. I recommend to use Object.assign instead of the second argument if you don't want to do anything special:

Object.assign(Object.create(element_structure.StaticTextField), {
    label_multilanguage_key: ML_KEYS.first_name,
    name: "first_name"
});

Upvotes: 4

Richik SC
Richik SC

Reputation: 884

Try checking hasOwnProperty in the loop:

for (var p in design_element) {
    if (design_element.hasOwnProperty(p)) console.log(p);
}

Upvotes: 0

Related Questions