- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to add properties from one object into another without overwriting in JavaScript?
Let’s say the following are our objects −
var first = {key1: 100, key2: 40, key3: 70} var second = {key2: 80, key3: 70, key4: 1000}
You can use the concept of hasOwnProperty() to add properties from one object to another. Following is the code −
Example
var first = {key1: 100, key2: 40, key3: 70} var second = {key2: 80, key3: 70, key4: 1000} function addPropertiesWithoutOverwritting(first, second) { for (var key2 in second) { if (second.hasOwnProperty(key2) && !first.hasOwnProperty(key2)) { first[key2] = second[key2]; } } return first; } console.log(addPropertiesWithoutOverwritting(first, second))
To run the above program, you need to use the following command −
node fileName.js.
Output
Here, my file name is demo99.js. This will produce the following output −
PS C:\Users\Amit\JavaScript-code> node demo99.js { key1: 100, key2: 40, key3: 70, key4: 1000 }
- Related Articles
- How to duplicate Javascript object properties in another object?
- How to add, access, delete, JavaScript object properties?
- How to update a MongoDB document without overwriting the existing one?
- How to add properties and methods to an object in JavaScript?
- Best way to flatten an object with array properties into one array JavaScript
- How to add properties and methods to an existing object in JavaScript?
- How to send data from one activity to another in Android without intent?
- How to insert values from one table into another in PostgreSQL?
- Extract properties from an object in JavaScript
- How to pass an object from one Activity to another in Android?
- How to Copy files or Folder without overwriting existing files?
- How to create object properties in JavaScript?
- How to delete object properties in JavaScript?
- How to copy Docker images from one host to another without using a repository?
- Remove number properties from an object JavaScript

Advertisements