Just started learning Javascript. I've been trying to wrap my head around it for hours, looking at examples, but still struggling.
I'm working with an array of objects that have nested properties which I need to loop through and consolidate.
var items = [{
name: "flat bread",
price: "5",
components: [
{ qty: 120, unit: "g", ingredient: { name: "flour", price: 1, perAmount: 1, unit: "kg" } },
{ qty: 250, unit: "mL", ingredient: { name: "milk", price: 4, perAmount: 3, unit: "litre" } },
{ qty: 1.5, unit: "g", ingredient: { name: "salt", price: 1.2, perAmount: 1, unit: "kg" } },
{ qty: 28.35, unit: "g", ingredient: { name: "butter", price: "6", perAmount: 500, unit: "g" } }
]
},
{
name: "pancake",
price: "15",
components: [
{ qty: 120, unit: "g", ingredient: { name: "flour", price: 1, perAmount: 1, unit: "kg" } },
{ qty: 250, unit: "mL", ingredient: { name: "milk", price: 4, perAmount: 3, unit: "litre" } },
{ qty: 2, unit: "each", ingredient: { name: "egg", price: 5, perAmount: 12, unit: "each" } },
{ qty: 12.5, unit: "g", ingredient: { name: "sugar", price: 2.20, perAmount: 2, unit: "kg" } }
]
},
{
name: "crepe",
price: "10",
components: [
{ qty: 120, unit: "g", ingredient: { name: "flour", price: 1, perAmount: 1, unit: "kg" } },
{ qty: 250, unit: "mL", ingredient: { name: "milk", price: 4, perAmount: 3, unit: "litre" } },
{ qty: 2, unit: "each", ingredient: { name: "egg", price: 5, perAmount: 12, unit: "each" } },
{ qty: 28.35, unit: "g", ingredient: { name: "butter", price: "6", perAmount: 500, unit: "g" } }
]
}
];
consolidatedComponents = items.map((item) => {
return { components: item.components }
});
console.log(consolidatedComponents);
I'm aiming to achieve a result similar to this:
- 360g flour
- 750ml milk
- 1.5g salt 4 eggs
- 12.5g sugar
- 56.7g butter
I understand I'll need to convert units later on, assuming they're consistent across all items/ingredients.