Last active
June 11, 2020 15:41
-
-
Save leonidkuznetsov18/3606fe9fc93ff46fe95c7bfb51f3c0ce to your computer and use it in GitHub Desktop.
recursive update value inside nested objects
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 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