Skip to content

Instantly share code, notes, and snippets.

@c01nd01r
Created April 1, 2021 01:16
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 c01nd01r/642ad6e09c30dd1fba6c0410b00afa0a to your computer and use it in GitHub Desktop.
Save c01nd01r/642ad6e09c30dd1fba6c0410b00afa0a to your computer and use it in GitHub Desktop.
Set value to object by path
// 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