将命名对象添加到数组

Add named objects to array

我正在尝试为添加到数组的对象创建键。

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

当我在下面记录小部件时,控制台中没有返回任何内容,或者没有 object/widget 被添加到小部件数组。

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");
});

widgets[widget.handle] 期望 widgets 是一个对象。

您应该直接推送到小部件。

widgets.push(widget);

或者如果你想保持你的结构,你应该将小部件定义为一个对象。

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