1

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.

2
  • So, you have a function that return an object, and then you are storing the objects returned by the function inside an array or just want to update an starting empty object progressively with the returned objects? Commented Jun 4, 2019 at 2:46
  • The function returns the object like {"myType1": ["123"]}, as each object is being recieved I want to collage into one Commented Jun 4, 2019 at 2:52

3 Answers 3

2

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);

Sign up to request clarification or add additional context in comments.

Comments

0

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; }

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.