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

Grouping values into one array of objects from two objects based on differing keys

I need to group two objects into an array of objects.

Beginning objects:

{strIngredient1: 'Light rum', 
strIngredient2: 'Lime', 
strIngredient3: 'Sugar', 
strIngredient4: 'Mint', 
strIngredient5: 'Soda water'}

{strMeasure1: '2-3 oz ', 
strMeasure2: 'Juice of 1 ', 
strMeasure3: '2 tsp ', 
strMeasure4: '2-4 '}

I would like the final array of object to look like this:

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

[
   {ingredient: 'Light rum', measure: '2-3 oz'},
   {ingredient: 'Lime', measure: 'Juice of 1'},
   etc... (if no measure, fill with empty string)
]

I have tried parsing the objects into two arrays based on keys and values, then looping through both arrays and outputting the values based on the number in the keys, however there has to be a more efficient way of getting the desired outcome. Any suggestions?

>Solution :

You can loop over the keys of the ingredients object and create the desired array by slicing out the ingredient number and looking for the corresponding measure for that number.

const 
  ingredients = { strIngredient1: "Light rum", strIngredient2: "Lime", strIngredient3: "Sugar", strIngredient4: "Mint", strIngredient5: "Soda water" },
  measurements = { strMeasure1: "2-3 oz", strMeasure2: "Juice of 1", strMeasure3: "2 tsp", strMeasure4: "2-4" },
  result = Object.keys(ingredients).map((k) => ({
    ingredient: ingredients[k],
    measure: measurements[`strMeasure${k.slice(13)}`] ?? "",
  }));

console.log(result);
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