Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to assign an array of objects to an object?

I have the following object and array of objects the later is a server array and the first one is a reference object that I want to use to get the values that I want from the main array and idea how to intigrate the array in to the object ? I tried to use Object.assign but no luck.

const obj1 = { day1: ['cake', 'muffin'], day2: ['grapes']};
const arrObj2: = [{name : 'cake', group 'dessert'},{name : 'muffin', group 'dessert'},{name : 'grapes', group 'vegs'}]
// Expected results 
const newObject = //{ 
                  //  day1: [{name : 'cake', group 'dessert'},{name : 'muffin', group 'dessert'}]
                  //, day2: [{name : 'grapes', group 'vegs'}]
                  //};

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You should use a .reduce to map thru all entries [key, value] fromobj1 and then filter items from arrObj2 where name is in your value array

const newObject = Object.entries(obj1).reduce((p, [key, value]) => ({
  ...p,
  [key]: arrObj2.filter(f => value.includes(f.name))
}), {})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading