Updating the Value of an Object in Javascript: A Guide

There are a couple of options for replacing values in JS objects and arrays without repetition. One approach is to have getObject() return an object, onto which you can set the field value. Alternatively, you can create a function that assigns the field value instead. Another possibility is to wrap your values in objects, so that getObject never returns null. In this case, you would return an empty object and set the field value on it. The current method involves returning the value stored in a, storing it in a variable, and then modifying the value in the new variable. Solution 2:


Solution:

A function named

updateNestedObj()

can be created to apply updates recursively to each object and its child objects.

const objToUpdate = { children : [ { children : [ { children : [ { id : "F100517B-D00F", level : 4, note : "update me", parentId : "23A2A0DB-CCE3", title : "change me" } ], id : "23A2A0DB-CCE3", level : 3, note : "me too", parentId : "a0H4H00000Roi", title : "..and me" } ], id : "a0H4H00000Roi", level : 2, note : "none", parentId : "0064H00000ysL", title : "pending" }, { "children" : [ { id : "6A45E2EC-7825", level : 3, note : "|", parentId : "a0H4H00000Roi", title : "" } ], id : "a0H4H00000Roi", level : 2, note : "", parentId : "0064H00000ysL", title : "Change me" } ], id : "0064H00000ysL", level : 1, note : "hello", title : "Test Co" } 
const updateArr = [{ content: "New Co", id: "0064H00000ysL", note: "Here's your update" }, { content: "91%", id: "a0H4H00000Roi", note: "New note here" }];
function updateNestedObj(obj, updates) {
    const updateToApply = updates.find(upd => upd.id === obj.id);
    if (updateToApply) {
        obj.title = updateToApply.content;
        obj.note = updateToApply.note;
    }
    // Apply updates to any child objects
    for(let k in obj) {
        if (typeof(obj[k]) === 'object') {
            updateNestedObj(obj[k], updates);
        }
    }
}
updateNestedObj(objToUpdate, updateArr);
console.log(objToUpdate)
        

.as-console-wrapper { max-height: 100% !important; top: 0; }

Frequently Asked Questions