Home > Back-end >  One of the values of my object should be an array of objects, but instead of pushing the inner objec
One of the values of my object should be an array of objects, but instead of pushing the inner objec

Time:08-31

I am trying to create an array of objects with the following stricture

obj {
name : name,
items : []
} 

where items should be an array of item objects like this

item {
itemName : itemName, 
price : price
}

when I try to add a second item object to the array, it creates instead another of the outer object

function catalogue(input) {
    let catalogue = [];

    for (let line of input) {
        let [name, price] = line.split(" : ")
        let catalogueLetter = name[0];
        let obj = {
            name: name[0],
            items: []
        }

        if (!catalogue.includes(catalogueLetter)) {
            catalogue.push(obj)
        }
        let innerObject = {
            productName: name,
            productPrice: price
        }
        obj.items.push(innerObject)

    }
   }
}

catalogue([
    'Omlet : 5.4',
    'Shirt : 15',
    'Cake : 59',
    'Carrot : 2'
])

and I am getting this:

[
  { name: 'C', items: [ [Object] ] },
  { name: 'C', items: [ [Object] ] },
  { name: 'O', items: [ [Object] ] },
  { name: 'S', items: [ [Object] ] }
] 

and I am trying to get this :

[
  { name: 'C', items: [ [Object1, Object2] ] },
  { name: 'O', items: [ [Object] ] },
  { name: 'S', items: [ [Object] ] }
]

CodePudding user response:

Try this:

if (!catalogue.some(cat => cat.name === catalogueLetter)) {
  catalogue.push(obj)
}

instead of this:

if (!catalogue.includes(catalogueLetter)) {
  catalogue.push(obj)
}

!catalogue.includes(catalogueLetter) is always true, because catalogue is an array of objects and not array of strings.

  • Related