Benjamin
Benjamin

Reputation: 697

Add named objects to array

I am trying to create keys for objects that are added to an array.

widgets [
"hats": {widget},
"shirts": {widget},
...
...
]

When I log widgets below nothing is returned in the console or no object/widget is being added to the widgets array.

let widgets = [];
$(document).on("change",'select.filter-select, .filter-checkbox input', function(e) {
    const widget    = {};
    const $this = $(this);

    if ( $this.hasClass('checkbox') ) {
        widget.type         = $this.data('type');
        widget.blueprint    = $this.data('blueprint');
        widget.handle       = $this.data('handle');
        widget.url          = $this.data('url');
    }
    else{
        const option        = $('option:selected', this);
        widget.type         = option.parent().data('type');
        widget.blueprint    = option.parent().data('blueprint');
        widget.handle       = option.data('handle');
        widget.url          = option.data('url');
    }

    if ( widgets.length > 0 ) {
        $.each(widgets, function (key,value) {
            if (!widgets[widget.handle]) {
                widgets[widget.handle].push(widget);
            }
        });
    }
    else {
        widgets[widget.handle].push(widget);
    }
    console.log(widgets + "\n\n");
});

Upvotes: 0

Views: 62

Answers (1)

Chris Chen
Chris Chen

Reputation: 1293

widgets[widget.handle] is expecting widgets to be an object.

You should push directly to widgets.

widgets.push(widget);

Or you should define widgets as an object if you want to keep your structure.

const widgets = {}
...
widgets['widget.handle'] = widget

Upvotes: 1

Related Questions