Transform an object with objects in it
function transform(obj) {
return Object.entries(obj).reduce((newObj, [name, value]) => ({ ...newObj, [name]: value.value === undefined ? transform(value) : value.value }), {})
}
const form = {
id: {value: '77777', hidden: true},
title: {value: '11111'},
translations: {
en: {
locale: {value: 'en', hidden: true},
name: {value: 'Hello World'}
},
nl: {
locale: {value: 'nl', hidden: true},
name: {value: 'Hallo Wereld'}
}
}
}
console.log(transform(form))
Explanation:
function transform(obj) {
const entries = Object.entries(obj) // transform object to Array<[propertyName, propertyValue]>
const tranformedObject = entries.reduce(reducer, {}) // inital value for the first arg of reducer is {}
return tranformedObject
}
function reducer(newObj, [propertyName, propertyValue]) { // name
return {
...newObj, // get all properties (that we already set) from prev newObj
[propertyName]: propertyValue.value === undefined ? transform(propertyValue) : propertyValue.value // if property has .value use it or use recursively tranformed object
} // returned value will be set to newObj, and than returned to tranformedObject
}
{ ...prop, [name]: vaue }
- it's ES6 syntax