I am looking for a way to merge many objects with the same key to a one big object. The number of objects can be more that 2.
For example I have this code:
const a = {
en: {
hello: 'Hello'
},
fr: {
hello: 'Bonjour'
}
}
const b = {
en: {
goodbye: 'Goodbye'
},
fr: {
goodbye: 'Au revoir'
}
}
How to merge that into this:
{
locale: 'en',
messages: {
en: {
hello: 'Hello',
goodbye: 'Goodbye'
},
fr: {
hello: 'Bonjour',
goodbye: 'Au revoir'
}
}
}
You could use a deep merge function for every level of the object.
The function deepMerge
works as single function for a given target or as callback for Array#reduce
, where an array of objects is iterated and an empty object is supplied as startvalue
for reducing.
As result, you need a new object and assign the merges objects as new property messages
.
function deepMerge(target, source) { Object.entries(source).forEach(([key, value]) => { if (value && typeof value === 'object') { deepMerge(target[key] = target[key] || {}, value); return; } target[key] = value; }); return target; } var a = { en: { hello: 'Hello' }, fr: { hello: 'Bonjour' } }, b = { en: { goodbye: 'Goodbye' }, fr: { goodbye: 'Au revoir' } }, c = { locale: 'en', messages: [a, b].reduce(deepMerge, {}) }; console.log(c);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Function mergeArray for array merging
const mergeArray = (firstArray, secondArray) => {
return {
locale: 'en',
messages: {
en: {
...firstArray.en,
...secondArray.en
},
fr: {
...firstArray.fr,
...secondArray.fr
}
}
}
};
console.log(mergeArray(a, b));
Below snippets give you expected output.
const value = { locale: 'en', messages: { en: { ...a.en, ...b.en }, fr: { ...a.fr, ...b.fr } }};
console.log(value)
If you want it to a new object, you can use Object.Assign({}, a, b)
read this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
Try this when the number of objects is dynamic:
var o, k, v, n, A=[a,b], r={}
for(o in A) for(k in A[o]) if(!r[k]) r[k]={};
for(o in A) for(v in A[o]) for(n in A[o][v]) if(!r[v][n]) r[v][n]= A[o][v][n];
console.log(r);
console.log({locale: 'en',messages:r});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.