The requirement for my object is to have an array of nested objects. However, instead of adding the inner objects to the array, it mistakenly creates new outer objects

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] ] }
]

Answer №1

Consider using the following approach:

if (!library.some(lib => lib.name === libraryLetter)) {
  library.push(object)
}

Rather than using:

if (!library.includes(libraryLetter)) {
  library.push(object)
}

The expression !library.includes(libraryLetter) will always be evaluated as true, since library is an array of objects and not a simple array of strings.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to reduce the size or simplify the data in similar JSON objects using Node.js and NPM packages?

Is it possible to serialize objects of the type "ANY_TYPE" using standard Node tools.js or NPM modules? There may be multiple objects with this property. Original Json - https://pastebin.com/NL7A8amD Serialized Json - https://pastebin.com/AScG7g1R Thank ...

Setting up a recurring task with a while loop in a cron job

Discover numerous libraries dedicated to implementing cron jobs in NodeJS and Javascript, allowing for hosting on a server. Ultimately, cron jobs are simply repetitive tasks set to run at specific times/dates. This led me to ponder the distinction betwee ...

Tips for building a task list using JavaScript only

Is it possible to create a to-do list using only JavaScript in an HTML file with a single div tag? Here is my HTML file for reference: example Here is the structure of my HTML file... <!DOCTYPE html> <html lang="en"> <head> ...

Is there a way to use moment js to change the date format to just show the month and year?

Want to transform the date time format using momentjs 2017-02-01T00:00:00.000Z into 02-2017 ( month-year ) Looking for a way to change the date format to display only month-year using momentjs? I attempted it like this: var MnthYr = moment(2017-02-01 ...

Discover the Phillips Hue Bridge within the operational web application on a separate network

Utilizing the node-hue-api package on a Node.js/Express server to interact with the Hue API, I've developed an admin section of a website exclusively accessible to me for controlling my Hue lights. The functionality works seamlessly in my local develo ...

Creating a multi-dimensional array in R can be easily achieved by using

Is there a way to create a multi-dimensional array in R? I attempted courses <- 1:12 for (i in 1:300) { list[i] <- sample(courses, size=3, replace=FALSE) } However, I am encountering this warning message: In list[i] <- sample(courses, size ...

What is the best way to interpret varbinary data from SQL as a string using C#?

Currently, I am working on a web application that retrieves varbinary data from SQL and converts it into a byte array in the code using ExecuteScalar. Now, I am creating a Windows application version of this project where I want to bypass the DB connecti ...

Is it possible to utilize jQuery to assign an image's src to the src of a different image located on the same webpage?

I am facing a challenge where I need to change the image source of an image on my webpage to match another image's source. Is there a way to accomplish this using jQuery? My attempted solution: $('#existingLogoImage').attr('src', ...

Display a JavaScript dialogue box containing a PHP variable

Is there a way to display the correct JavaScript box when using a While loop in PHP? Here is the code snippet: while($result= mysql_fetch_array($data)){ <tr class="<?php echo $style;?>"> <td><?php echo $result['commis ...

JavaScript - Unable to unselect a button without triggering a page refresh

I have a series of buttons in a row that I can select individually. However, I only want to be able to choose one button at a time. Every time I deselect the previously selected button, it causes the page to reload when all I really want is for all the but ...

Utilize JSON text importing for template literals in Node.js

When it comes to my node js projects, I usually opt for using a text.json file and requiring it rather than hardcoding static text directly into my code. Here's an example: JSON file { "greet": "Hello world" } var text = require('./text.json ...

Getting URL Parameters in Angular JS

How should one go about retrieving URL parameters in Angular? For instance, consider this URL: http://example.com/mypage.html?product=1234®ion=4&lang=en Thank you ...

What is the process of combining two string-type lists into a list object?

Let's assume we have a class named Transaction: public class Transaction { private String tId; private String tStatus; } Next, we create another class called Customer: public class Customer { private String cId; private List<T ...

What is the best way to assign a distinct index value to each object in an array

When I use the function below to add an index to each array object, all IDs end up with the same value when I check console.log: var foo = [...this.props.articleList]; foo.forEach(function(row, index) { row.id = index+1; }); console.log(foo); My des ...

Is it possible to retrieve an element by its id, save it in a variable, and then add it to an li element?

Just delving into the world of JS and attempting to create a simple to-do list. Even after completing tutorials on CodeAcademy and TreeHouse where I learned about functions, if statements, loops, objects, etc., it seems like none of it really sticks until ...

Implementing AJAX requests in jQuery DataTable with ASP.NET MVC

For some time now, I have been using the jQuery DataTables 1.10.13 plugin. Recently, I encountered an issue related to the ajax data source for my HTML table. This is how I initialized jQuery DataTable inside Files.cshtml <script language="javascript" ...

What is the best way to assign specific tasks to various user roles?

In my management system, users can register and manage the platform using CRUD operations. I want to restrict the privilege of adding, updating, and deleting other users only to the admin role. If a user is not an admin, they should only be able to use the ...

Is there a method to prompt Angular to alert me when utilizing an undeclared directive in a template?

At times, I find myself making typos in the angular directive's name or the element tag within its template. However, the only indication I receive is the directive mysteriously disappearing. It would be helpful if angularjs could alert me when I at ...

Ensure that the default boolean value is set to false rather than being left as undefined

I have a specific type definition in my code: export type ItemResponse = { .... addedManually: boolean; .... } Whenever I parse a JSON response into this type, I encounter an issue: const response = await fetch( `https://api.com` ); con ...

trouble with fetching data

Within my Backbone view, I have the following code snippet: var BookView = Backbone.View.extend({ initialize: function() { this.render(); }, render: function() { this.model.fetch({ success : function(model, resp, opt) { alert(this.$el. ...