0

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");
});
Benjamin
  • 697
  • 1
  • 8
  • 32

1 Answers1

1

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
Chris Chen
  • 1,228
  • 9
  • 14
  • This worked but how can I now check if any objects have been added to the Widgets object, widgets.length > 0 no longer works returns undefined? What I am trying to do is if widget has already been added into Widgets, don't add it again but remove it. Think if a checkbox is checked and unchecked – Benjamin Oct 14 '19 at 23:08
  • 1
    If you just want to check if widget is empty to replace `if ( widgets.length > 0 )`, then consider using any methods mentioned in here https://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object – Chris Chen Oct 15 '19 at 00:36