Suppose, we have two JavaScript objects defined like this −
const a = {
a: 1,
af: function() { console.log(this.a) },
};
const b = {
b: 2,
bf: function() { console.log(this.b) },
};We are required to write a JavaScript function that takes in two such objects. Create another object which will get the properties of a and b, like this −
const output = {
a: 1,
af: function() { console.log(this.a) },
b: 2,
bf: function() { console.log(this.b) },
}Note that a and b need to stay the same.
Example
The code for this will be −
const a = {
a: 1,
af: function() { console.log(this.a) },
};
const b = {
b: 2,
bf: function() { console.log(this.b) },
};
const extend = function(){
let i, j, x, res=(arguments[0] || {});
for (i = 1; i < arguments.length; i++) {
const x = arguments[i];
for (j in x) {
if (x.hasOwnProperty(j)) {
res[j] = x[j];
}
}
}
return res;
};
const c = extend({}, a, b);
console.log(c);Output
And the output in the console will be −
{ a: 1, af: [Function: af], b: 2, bf: [Function: bf] }