Created
April 1, 2021 01:16
-
-
Save c01nd01r/642ad6e09c30dd1fba6c0410b00afa0a to your computer and use it in GitHub Desktop.
Set value to object by path
This file contains 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
// original https://stackoverflow.com/a/7070222/5485802 | |
const set = (root, segments, value) => { | |
let lastField = root; | |
let segment; | |
let i; | |
for (i = 0; i < segments.length - 1; ++i) { | |
segment = segments[i]; | |
lastField = lastField[segment] = lastField[segment] || {}; | |
} | |
lastField[segments[i]] = value; | |
}; | |
// for zod@3 -> errors object | |
const objectErrors = (issues) => { | |
const errorFields = {}; | |
issues.forEach((issue) => { | |
set(errorFields, issue.path, issue.message); | |
}) | |
return errorFields; | |
} | |
console.log( | |
objectErrors([ | |
{path: ['a', 'b', 'c'], message: 'some error C'}, | |
{path: ['a', 'b', 'd'], message: 'some error D'}, | |
]) | |
) | |
const setR = (segments, value) => { | |
return segments.reduceRight((acc, segment) => ({ [segment]: acc }), value); | |
} | |
console.log( | |
setR(['a', 'b', 'c'], 4242) | |
); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment