Last active
July 9, 2021 13:07
-
-
Save AndrewEastwood/ee91b9254ea36756365df3f23328722c to your computer and use it in GitHub Desktop.
set/update value in an object
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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