Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save leonidkuznetsov18/3606fe9fc93ff46fe95c7bfb51f3c0ce to your computer and use it in GitHub Desktop.

Select an option

Save leonidkuznetsov18/3606fe9fc93ff46fe95c7bfb51f3c0ce to your computer and use it in GitHub Desktop.
recursive update value inside nested objects
const fieldErrors = {
name: {
error: 'name.exists'
},
surname: {
field: {
error: 'surname.exists',
typeError: 'call.to.api.error',
},
errors: {
error: 123,
field: {
error: 'some.custom.error.from.backend',
},
},
},
};
// with forEach
const replaceErrors = obj => {
const clonedObj = { ...obj };
const entries = Object.entries(clonedObj);
entries.forEach(([key, value]) => {
if (typeof value === "object") {
clonedObj[key] = replaceErrors(value);
} else {
if (typeof clonedObj.error === 'string') {
clonedObj.error = "test";
}
}
});
return clonedObj;
};
console.log(replaceErrors(fieldErrors))
// with map and custom function
function replaceErrors(object, fn) {
return Object.fromEntries(Object
.entries(object)
.map(([k, v]) => [k, v && typeof v === 'object' ? replaceErrors(v, fn) : fn(v)])
);
}
const result = replaceErrors(fieldErrors, v => '111');
console.log(result);
// with reduce
function replaceErrors(obj) {
return Object.keys(obj).reduce((acc, key) => {
if (typeof obj[key] === 'object') {
acc[key] = replaceErrors(obj[key]);
} else {
if (key === 'error') {
acc = {
...obj,
error: typeof obj[key] === 'string' ? 'test' : obj[key]
}
}
}
return acc;
}, {});
}
console.log(replaceErrors(fieldErrors))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment