Created
September 7, 2023 13:44
-
-
Save dinocarl/f493315ec9219aa96fcb2942c51310ac to your computer and use it in GitHub Desktop.
Simple dependency-less assocPath function
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 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