Tengo estos dos objetos:
const tmp = { pl: { translation: { states: { foo: { name: 'bar' }, }, }, }, en: { translation: { states: { foo: { name: 'bar' }, }, }, }, }; const tmp2 = { pl: { translation: { states: { foz: { name: 'baz' }, }, }, }, de: { translation: { states: { foo: { name: 'bar' }, }, }, }, };¿Cómo puedo concatenarlos? la parte pl es fluida, puede cambiar por lo que tiene que ser dinámica.
Estaba pensando en hacerlo recursivamente con una combinación de Object.keys, pero parece una exageración.
lodash merge hará el truco aquí:
const tmp = { pl: { translation: { states: { foo: { name: 'bar' } } } }, en: { translation: { states: { foo: { name: 'bar' } } } }, }; const tmp2 = { pl: { translation: { states: { foz: { name: 'baz' } } } }, de: { translation: { states: { foo: { name: 'bar' } } } }, }; console.log(_.merge(tmp, tmp2)); <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"></script>Ahí tienes:
function merge(o1,o2){ const result = {} for(const key of Object.keys(o1)) result[key] = key in o2 ? merge(o1[key],o2[key]) : o1[key]; for(const key of Object.keys(o2)) if(!(key in o1)) result[key] = o2[key]; return result; }Sugeriría un enfoque más estándar, genérico y especialmente sin bibliotecas:
const extend = (isDeep, objects) => { // Variables let extended = {}; let deep = isDeep; // Merge the object into the extended object const merge = function (obj) { for (let prop in obj) { if (obj.hasOwnProperty(prop)) { if (deep && Object.prototype.toString.call(obj[prop]) === '[object Object]') { // If we're doing a deep merge and the property is an object extended[prop] = extend(deep, [extended[prop], obj[prop]]); } else { // Otherwise, do a regular merge extended[prop] = obj[prop]; } } } }; // Loop through each object and conduct a merge for (let argument of objects) { merge(argument) } return extended; };Y puedes usarlo simplemente llamando:
extend(true, [tmp, tmp2])El primer parámetro booleano se usa para realizar una fusión profunda o una fusión regular.