Skip to content

Instantly share code, notes, and snippets.

@dinocarl
Created September 7, 2023 13:44
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 dinocarl/f493315ec9219aa96fcb2942c51310ac to your computer and use it in GitHub Desktop.
Save dinocarl/f493315ec9219aa96fcb2942c51310ac to your computer and use it in GitHub Desktop.
Simple dependency-less assocPath function
const assocPth = ([head, ...rest], value, obj) => Array.isArray(obj)
? [].concat(
obj.slice(0, head),
[rest.length
? assocPth(rest, value, obj[head])
: value],
obj.slice(head + 1))
: Object.assign({},
obj,
{[head]: rest.length
? assocPth(rest, value, obj[head])
: value
});
const data = {
a: {
b: 2,
c: 3,
d: ['a', 'b'],
e: [
['f', 'g'], ['h', 'i'], [['j', 'k'], ['l', 'm', 'n', {o: 'p'}]]
],
},
d: {
e: 4
}
};
const pth = ['a', 'e', 2, 1, 3, 'o'];
assocPth(pth, 8, data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment