I am struggling to form an array of objects with the given structure
obj {
name : name,
items : []
}
In this setup, items should be an array consisting of item objects like so
item {
itemName : itemName,
price : price
}
However, when I attempt to insert a second item object into the array, it mistakenly creates another outer object instead
function catalog(input) {
let catalog = [];
for (let line of input) {
let [name, price] = line.split(" : ")
let catalogLetter = name[0];
let obj = {
name: name[0],
items: []
}
if (!catalog.includes(catalogLetter)) {
catalog.push(obj)
}
let innerObject = {
productName: name,
productPrice: price
}
obj.items.push(innerObject)
}
}
}
catalog([
'Omlet : 5.4',
'Shirt : 15',
'Cake : 59',
'Carrot : 2'
])
The result I am receiving is:
[
{ name: 'C', items: [ [Object] ] },
{ name: 'C', items: [ [Object] ] },
{ name: 'O', items: [ [Object] ] },
{ name: 'S', items: [ [Object] ] }
]
My goal is to achieve this :
[
{ name: 'C', items: [ [Object1, Object2] ] },
{ name: 'O', items: [ [Object] ] },
{ name: 'S', items: [ [Object] ] }
]