Merge two option-objects with function

Viewed 81

I plan to merge two objects that contain methods:

var options = {
    show: function() {
        console.log(1);
    }
}

var options2 = {
    show: function() {
        console.log(3);
    }
}

options = $.merge(options, options2);

But if I do console.log(options.show) I recieve only first array.

My question is, how to merge options array with options2?

3 Answers

You can call the oher function inside the first function block

var options = {
    show: function() {
        console.log(1);
        options2.show();
    }
}

var options2 = {
    show: function() {
        console.log(3);
    }
}

options.show();

Since 'same property' name, they will override when you merge. Use destructuring and rename and Object.assign should work.

var options = {
    show: function() {
        console.log(1);
    }
}

var options2 = {
    show: function() {
        console.log(3);
    },
    other: () => console.log('other')
}

const { show: show2, ...rest2 } = options2;

Object.assign(options, { show2 }, rest2);

options.show();
options.show2();
options.other();

You probably want something like this

var options = { show: function () { console.log(1); }, };
var options2 = { show: function () { console.log(3); }, };
res = Object.entries(options).map((o) => ({ [o[0]]: [o[1], options2[o[0]]] }));
console.log(res[0]);
console.log(res[0].show)

Related