Tengo una pregunta sobre los dos objetos anteriores:
const object1 = { issues: { global: 'a great string!' } }; const object2 = { issues: { cooldown: 'oh well, another message!' } };
Para el propósito de mi código, necesitaría fusionar todo pero mantener la jerarquía entre las propiedades. Como esto:
Object.assign(object1, object2); console.log(object1); // expected output: { issues: { global: 'a great string!', cooldown: 'oh well, another message!' } }
Excepto que el problema es que Object.assign() funciona de tal manera que sobrescribirá la propiedad anterior (aquí global ) para mantener solo la última propiedad (aquí cooldown ) . Como esto:
Object.assign(object1, object2); console.log(object1); // real output: { issues: { cooldown: 'oh well, another message!' } }
Entonces mi pregunta es simple: ¿cómo obtenemos el resultado esperado? Supongo que no es tan simple como un simple Object.assign() , pero precisamente: ¿cómo? Sabiendo que obviamente tomé aquí un ejemplo y que, en realidad, es imposible saber de antemano qué propiedades llegarán...
Gracias por la ayuda 💙
Creo que una solución recursiva ayudará para cualquier nivel de anidamiento:
const obj1 = { issues: { global: 'a great string!' } }; const obj2 = { issues: { cooldown: 'oh well, another message!' } }; const obj3 = { issues: { global: 'a great string!' } , problems : { name : 'cool' , size : { medium : 'ok', small : 'ok' } } }; const obj4 = { issues: { cooldown: 'oh well, another message!' } , problems : { name : 'cool' , size : { big : 'not ok', } } }; const merge = (obj1,obj2) => { const newObj = {}; for(let key in obj1){ if(typeof obj1[key] !== 'object'){ newObj[key] = obj1[key]; } else if(key in obj2){ newObj[key] = merge(obj1[key],obj2[key]); } else{ newObj[key] = obj1[key]; } } for(let key in obj2){ if(!(key in obj1)){ newObj[key] = obj2[key]; } } return newObj; }; console.log(merge(obj1,obj2)); console.log(merge(obj3,obj4));Verifica si las claves coinciden (disponibles en ambos objetos) y, en función de eso, agrega una nueva clave a su nuevo objeto de resultado.
Nota: Lo anterior por defecto maneja el caso cuando los valores de propiedad no son objects . Puede cambiar y agregar su comportamiento deseado
creo esta función creo que hará el trabajo
const obj1 = { issues: { global: 'a great string!' } }; const obj2 = { issues: { cooldown: 'oh well, another message!' } }; const obj3 = { issues: { global: 'a great string!' }, problems: { name: 'cool', size: { medium: 'ok', small: 'ok' } } }; const obj4 = { issues: { cooldown: 'oh well, another message!' }, problems: { name: 'cool', size: { big: 'not ok', } } }; const mergeObj = (obj1, obj2) => { const Obj1Keys = Object.keys(obj1) const Obj2Keys = Object.keys(obj1) const allKeys = [...new Set([...Obj1Keys, ...Obj2Keys])] const newObj = {} for (let i = 0; i < allKeys.length; i++) { const key = allKeys[i] if (typeof obj1[key] === "object" && typeof obj2[key] === "object") newObj[key] = mergeObj(obj1[key], obj2[key]) } return Object.assign(obj1, obj2, newObj) } console.log(mergeObj(obj3, obj4));