Update JavaScript object with another object, but only existing keys?

To update a JavaScript object with values from another object while only affecting existing keys, you can use hasOwnProperty() to check if a key exists in the source object before updating it.

Example

var markDetails1 = {
    'marks1': 78,
    'marks2': 65
};

var markDetails2 = {
    'marks2': 89,
    'marks3': 90
};

function updateJavaScriptObject(details1, details2) {
    const outputObject = {};
    Object.keys(details1)
        .forEach(obj => outputObject[obj] =
        (details2.hasOwnProperty(obj) ? details2[obj] : details1[obj]));
    return outputObject;
}

console.log(updateJavaScriptObject(markDetails1, markDetails2));
{ marks1: 78, marks2: 89 }

How It Works

The function iterates through all keys in the first object (details1). For each key, it checks if that key exists in the second object (details2) using hasOwnProperty(). If the key exists in the second object, it uses the value from there; otherwise, it keeps the original value from the first object.

Alternative Using Object.assign()

var source = { marks1: 78, marks2: 65 };
var updates = { marks2: 89, marks3: 90 };

function updateExistingKeys(source, updates) {
    const result = { ...source };
    Object.keys(source).forEach(key => {
        if (updates.hasOwnProperty(key)) {
            result[key] = updates[key];
        }
    });
    return result;
}

console.log(updateExistingKeys(source, updates));
{ marks1: 78, marks2: 89 }

Conclusion

Using hasOwnProperty() ensures that only existing keys in the target object are updated, preventing the addition of new properties. This approach maintains the original object structure while selectively updating values.

Updated on: 2026-03-15T23:18:59+05:30

983 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements