Skip to content Skip to sidebar Skip to footer

Write Data To A Nested Dictionary Given A "key Path" Of Unknown Length

I have a file for my app that holds (in a dictionary) general info about the app EG the settings. The main dictionary is: 'info': {} to write to the file, my write function takes

Solution 1:

If you have a JSON object and a key-path:

function updateSettings(settings, keyPath, value) {
  const keys = keyPath.split('.');
  const targetKey = keys.pop();
  let current = settings;
  for (let i = 0; i < keys.length; ++i) {
    current = current[keys[i]];
    if (!current) {
      throw new Error('Specified key not found. ' + keys[i]);
    }
  }
  current[targetKey] = value;
  // return settings; // optional, because it changes settings object directly
}

const settings = {
  root: 0,
  settings: {
    appearance: 'light'
  },
  some: {
    very: {
      very: {
        nested: {
          value: 1
        }
      }
    }
  }
};

updateSettings(settings, 'settings.appearance', 'dark');
updateSettings(settings, 'root', 1024);
updateSettings(settings, 'some.very.very.nested.value', 2048);

the output is:

{
  root: 1024,
  settings: {
    appearance: 'dark'
  },
  some: {
    very: {
      very: {
        nested: {
          value: 2048
        }
      }
    }
  }
};

Some libraries (e.g. lodash _.get) have implementation methods for this.


Post a Comment for "Write Data To A Nested Dictionary Given A "key Path" Of Unknown Length"