I need convert ingredient to correct format, so I can use it further. All the data from form I put in Array by [... new FormData(NewRecipe)],
(15) [Array(2), Array(2), Array(2), Array(2), Array(2), Array(2), Array(2), Array(2), Array(2), Array(2), Array(2), Array(2), Array(2), Array(2), Array(2)]
0: (2) ['title', 'TEST23']
1: (2) ['sourceUrl', 'TEST23']
2: (2) ['image', 'TEST23']
3: (2) ['publisher', 'TEST23']
4: (2) ['cookingTime', '23']
5: (2) ['servings', '23']
6: (2) ['ingredient-1-1', '2']
7: (2) ['ingredient-1-2', 'kg']
8: (2) ['ingredient-1-3', 'Rice']
9: (2) ['ingredient-2-1', '1']
10: (2) ['ingredient-2-2', 'pieces']
11: (2) ['ingredient-2-3', 'Potato']
12: (2) ['ingredient-3-1', '55']
13: (2) ['ingredient-3-2', 'gramms']
14: (2) ['ingredient-3-3', 'salt']
length: 15
[[Prototype]]: Array(0)
then map through Array search for ingredients (NewRecipe) values:
const ingredients = newRecipe
.filter(entry => entry[0].startsWith('ingredient'))
.map(ing => {
const ingArr = ing[1].split(',').map(el=> el.trim());
});
const [quantity, unit, description] = ingArr
return {quantity, unit, description}
I extract each values, but I cannot put them in correct format. I need to return array of objects as below:
[{quantity:0.5, unit:'kg', description: 'Rice'},
{quantity:1, unit:'', description: "Avocado}]
CodePudding user response:
Have a filter and a reduce
You can skip the last step if your ingredients ALWAYS have 3 parts, then use the key2 to set the unit/qty/desc
const recipe = [
['title', 'TEST23'],
['sourceUrl', 'TEST23'],
['image', 'TEST23'],
['publisher', 'TEST23'],
['cookingTime', '23'],
['servings', '23'],
['ingredient-1-1', '2'],
['ingredient-1-2', 'kg'],
['ingredient-1-3', 'Rice'],
['ingredient-2-1', '1'],
['ingredient-2-2', 'pieces'],
['ingredient-2-3', 'Potato'],
['ingredient-3-1', '55'],
['ingredient-3-2', 'gramms'],
['ingredient-3-3', 'salt']
];
const ingrs = recipe
.filter(arr => arr[0].startsWith("ingredient-"))
.reduce((acc,cur) => {
const [_,key1,key2] = cur[0].match(/-(\d )-(\d )/)
acc[`i_${key1}`] = acc[`i_${key1}`] || [];
acc[`i_${key1}`].push(cur[1])
return acc
},{})
const ingrObjectArray = Object.values(ingrs).map(arr => ({qty:arr[0],unit:arr[1],desc:arr[2]}))
console.log(ingrObjectArray)