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

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

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
If you just want to check if widget is empty to replace if ( widgets.length > 0 ), then consider using any methods mentioned in here stackoverflow.com/questions/679915/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.