[Solved] need help to update the values in an object


It looks like you’ve overcomplicated the problem. It can be as simple as

function updateObj(obj,keyName,val) {
   obj[keyName] = val;
   return obj;
}

const bag = {
    color: 'yellow',
    hasMoney: false
}
console.log(updateObj(bag, 'color', 'Blue')); // => { color: 'Blue', hasMoney: false }

const house = {
    sqFt: 1500,
    isOccupied: true
}
console.log(updateObj(house, 'sqFt', 2000)); // => { sqFt: 2000, isOccupied: true }

const cat = { isFurry: false };
const propName="isFurry";

cat['propName'] = true;
console.log(cat); // => { isFurry: false, propName: true }

updateObj modifies the input object and sets a property. At the end it returns the reference to the input object. You can discard the return statement if you don’t need it

function updateObj(obj,keyName,val) {
   obj[keyName] = val;
}

const bag = {
    color: 'yellow',
    hasMoney: false
}
updateObj(bag, 'color', 'Blue');
console.log(bag); // => { color: 'Blue', hasMoney: false }

const house = {
    sqFt: 1500,
    isOccupied: true
}
updateObj(house, 'sqFt', 2000);
console.log(house); // => { sqFt: 2000, isOccupied: true }

const cat = { isFurry: false };
const propName="isFurry";

cat['propName'] = true;
console.log(cat); // => { isFurry: false, propName: true }

Creating a shallow copy using the spread operator is even simpler

function updateObj(obj,keyName,val) {
   return { ...obj, [keyName]: val };
}

const bag = {
    color: 'yellow',
    hasMoney: false
}
console.log(updateObj(bag, 'color', 'Blue')); // => { color: 'Blue', hasMoney: false }

const house = {
    sqFt: 1500,
    isOccupied: true
}
console.log(updateObj(house, 'sqFt', 2000)); // => { sqFt: 2000, isOccupied: true }

const cat = { isFurry: false };
const propName="isFurry";

cat['propName'] = true;
console.log(cat); // => { isFurry: false, propName: true }

but in that case the function name could be confusing, because the input object isn’t updated.

2

solved need help to update the values in an object