Skip to content

Instantly share code, notes, and snippets.

@AndrewEastwood
Last active July 9, 2021 13:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AndrewEastwood/ee91b9254ea36756365df3f23328722c to your computer and use it in GitHub Desktop.
Save AndrewEastwood/ee91b9254ea36756365df3f23328722c to your computer and use it in GitHub Desktop.
set/update value in an object
const mapper5 = (keys, v, o) => {
if (keys.length === 0) {
return o;
}
if (keys.length === 1) {
return { ...o, [keys[0]]: v };
}
const key = keys[0];
const isNextKeyForArray = /[0-9]+/.test(keys[1] || '');
const isPlainArrayValue = isNextKeyForArray && keys.length === 2;
const arrayKey = isNaN(parseInt(keys[1])) ? -1 : parseInt(keys[1]);
const child = isNextKeyForArray && arrayKey >= 0 ? o[key] || new Array(arrayKey + 1).fill({}) : o[key] || {};
return {
...o,
[key]: isNextKeyForArray ?
child.map((i, idx) => idx === arrayKey ? (isPlainArrayValue ? v : mapper5(keys.slice(2), v, i)) : i)
: { ...child, ...mapper5(keys.slice(1), v, child) }
};
}
// some tests:
mapper5('a.2'.split('.'), 3, {});
// "{\"a\":[{},{},3]}"
JSON.stringify(mapper5('a.2.c'.split('.'), 3, {}))
// "{\"a\":[{},{},{\"c\":3}]}"
JSON.stringify(mapper5('a.b.c'.split('.'), 3, {}))
// "{\"a\":{\"b\":{\"c\":3}}}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment