79684811

Date: 2025-06-30 13:14:32
Score: 0.5
Natty:
Report link

Maybe someone is interested in a solution, that allows to insert missing keys on any level of an existing object (without loosing existing keys/content):

const keyChain = ['opt1', 'sub1', 'subsub1', 'subsubsub1'];
const value = 'foobar';
const item = { 'foo': 'bar', 'opt1': { 'hello': 'world' }, };    
let obj = item;  // this assignment is crucial to keep binding to item level when looping through keyChain
const maxIdx = keyChain.length - 1;
keyChain.forEach((key, idx) => {  // walk through resp. build target object
  obj = obj[key] = idx < maxIdx ? obj[key] || {} : value;  // assign value to deepest key 
});
console.log(item);
Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Unregistered user (0.5):
  • Low reputation (1):
Posted by: Yves