Reputation: 8970
I have a function that returns an object like (key is string and value is array of strings):
{"myType1": ["123"]}
I want to merge all the results its returning for example - if I have:
{"myType1": ["123"]}
{"myType2": ["456"]}
{"myType1": ["789"]}
I'd like to get
{"myType1": ["123", "789], "myType2": ["456"]}
I've seen Object.assign
however that doesn't merge the values it just replaces with the most recent.
Has anyone got an examples of how I can achieve this?
Any help appreciated.
Thanks.
Upvotes: 1
Views: 144
Reputation: 1532
Here is a one liner with the desired process:
Array.from(new Set([{"myType1": ["123"]}, {"myType2": ["456"]}, {"myType1": ["789"]}].map(item => Object.keys(item)[0]).sort())).map(e => { const entry = {}; entry[e] = items.filter(item => Object.keys(item)[0] === e).map(item => item[e][0]); return entry })
Result:
[ { myType1: [ '123', '789' ] }, { myType2: [ '456' ] } ]
Regards.
Upvotes: 0
Reputation: 44125
Make a function that adds each property to a result object, and call it with each object you get.
let res = {};
const addObj = obj => {
Object.entries(obj).forEach(([k, v]) => (res[k] = res[k] || []).push(...v));
};
addObj({"myType1": ["123"]});
addObj({"myType2": ["456"]});
addObj({"myType1": ["789"]});
console.log(res);
.as-console-wrapper { max-height: 100% !important; top: auto; }
Upvotes: 0
Reputation: 26844
You can the keys of an object by using Object.keys
. Use forEach
to loop thru the keys and modify the result
object.
var result = {};
function mergeObj(o) {
Object.keys(o).forEach(k=>{
result[k] = ( result[k] || [] ).concat(o[k]);
})
}
mergeObj({"myType1": ["123"]});
mergeObj({"myType2": ["456"]});
mergeObj({"myType1": ["789"]});
console.log(result);
Upvotes: 2