

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Create an object based on 2 others in JavaScript
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] }
- Related Questions & Answers
- Filter an object based on an array JavaScript
- Constructing 2-D array based on some constraints in JavaScript
- Filter the properties of an object based on an array and get the filtered object JavaScript
- Manipulate Object to group based on Array Object List in JavaScript
- Build maximum array based on a 2-D array - JavaScript
- JavaScript - Sort key value pair object based on value?
- Python Pandas - Create an Index based on an underlying Categorical
- Shuffling string based on an array in JavaScript
- Sort object array based on another array of keys - JavaScript
- Modify an array based on another array JavaScript
- Encrypting a string based on an algorithm in JavaScript
- Shifting string letters based on an array in JavaScript
- How to create Python objects based on an XML file?
- How to create an ID column in R based on categories?
- Splitting an array based on its first value - JavaScript
Advertisements