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:
[
{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?
CodePudding user response:
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);
CodePudding user response:
You could separate the keys and build a new object.
const
data = [{ 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 ' }],
keys = { strIngredient: 'ingredient', strMeasure: 'measure' },
result = data.reduce((r, o, i) => {
Object.entries(o).forEach(([key, value]) => {
const [, k, i] = key.match(/^(.*?)(\d )$/);
(r[i - 1] ??= { ingredient: '', measure: '' })[keys[k]] = value;
});
return r;
}, []);
console.log(result);