简体   繁体   中英

How do i change the value of a key of a nested object in javascript

i have an object variable with nested keys like this

const obj = {
  kitchen: {
    painting: 100,
    piano: 1000,
    signature: "",
  },
  bathroom: {
    stereo: 220,
    signature: "",
  },
  signature: "",
};

i want to created a function that changes the value for the key "signature" with a name in both the root obj and any nested object that has a key "signature".

so:

function addSignature( obj , name){
}

returns

newObj = {
  kitchen: {
    painting: 100,
    piano: 1000,
    signature: name,
  },
  bathroom: {
    stereo: 220,
    signature: name,
  },
  signature: name,
};

i just made this and it works but idk if it is too "hacky"

function addSignature(obj, name) {
  if (obj.signature !== undefined) {
    obj.signature = name;
  }
  Object.keys(obj).forEach((key) => {
    if (typeof obj[key] === "object") {
      addSignature(obj[key], name);
    }
    else if (obj[key].signature !== undefined) {
      obj[key].signature = name;
    }
  });
  
  return obj;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM