-3

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,
};
ludinj
  • 107
  • 7
  • 2
    Where are you stuck here, exactly? If you haven't attepted implementing this, give it a try, then share your code if you get stuck. Also, consider providing detailed specification, like, is the object infinitely deep/nested and does it contain arrays and objects, or do you want the function to just work on this one structure? Thanks. – ggorlen Apr 09 '22 at 21:20
  • im learning javascript and im not sure how to iterate over objects the object only contains other objects but it can be infinitely nested. – ludinj Apr 09 '22 at 21:26
  • 1
    Thanks for the response -- does [How to iterate over a JavaScript object?](https://stackoverflow.com/questions/14379274/how-to-iterate-over-a-javascript-object) help? – ggorlen Apr 09 '22 at 21:46
  • i just posted an answer by doing some research and it works can you check it and tell me if it is bad code please? – ludinj Apr 09 '22 at 23:56

1 Answers1

1

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;
}
ludinj
  • 107
  • 7
  • You might be missing an else statement so if `obj` is `undefined` then you might run into some errors. You're using the variable `obj` without checking that it's not `undefined`, if you want to fix that then you should move the `.forEach()` function within the curly brackets of the `if(obj.signature !== undefined)` – Liam Apr 13 '22 at 08:11