Creating JSON files in JavaScript - Issue with adding data

My goal is to generate a unique JSON dataset structured in the following way: JSON:

    {
        "category": {
            "id": "10100",
            "name": "Dessert",
            "products": [
                {
                    "id": "10101",
                    "name": "Cheese Cake",
                    "description": "New York Style",
                    "price": 1.55,
                    "price_before_discount": 1.55,
                    "imageURL": "image2.jpg"
                },
                {
                    "id": "10102",
                    "name": "Apple Pie",
                    "description": "Old Fashion Home Made Pie.",
                    "price": 1.75,
                    "price_before_discount": 1.75,
                    "imageURL": "image3.jpg"
                }
            ],
            "id": "10104",
            "name": "Breakfast",
            "products": [
                {
                    "id": "10104",
                    "name": "Ham and Eggs",
                    "description": "With Hash Browns and Toast.",
                    "price": 4.75,
                    "price_before_discount": 4.75,
                    "imageURL": "image4.jpg"
                }
            ]
        }
    }

Javascript code:

    var menu = {};
    var category = {}
    var products = []
    
    menu.category = category;
    
    var catID = "10100";
    var catName = "Dessert";
    
    var catItems = {
        "id": catID,
        "name": catName
    }
    Object.assign(menu.category, catItems)
    
    menu.category.products = products;
    
    var itemID = "10101";
    var itemName = "Cheese Cake";
    var itemDescription = "New York Style"
    var itemPrice = 1.55
    var itemPrice_before_discount = 1.55
    var itemImageURL = "image.jpg"
    
    var items = {
        "id": itemID,
        "name": itemName,
        "description": itemDescription,
        "price": itemPrice,
        "price_before_discount": itemPrice_before_discount,
        "imageURL": itemImageURL
    }
    
    menu.category.products.push(items);
    
    var itemID = "10102";
    var itemName = "Apple Pie";
    var itemDescription = "Old Fashion Home Made Pie."
    var itemPrice = 1.75
    var itemPrice_before_discount = 1.75
    var itemImageURL = "image.jpg"
    
    var items = {
        "id": itemID,
        "name": itemName,
        "description": itemDescription,
        "price": itemPrice,
        "price_before_discount": itemPrice_before_discount,
        "imageURL": itemImageURL
    }
    
    menu.category.products.push(items);
    
    var cat2ID = "10102";
    var cat2Name = "Breakfast";
    
    catItems = {
        "id": cat2ID,
        "name": cat2Name
    }
    Object.assign(menu.category, catItems)
    
    menu.category.products = products;
    
    var itemID = "10104";
    var itemName = "Ham and Eggs";
    var itemDescription = "With Hash Browns and Toast"
    var itemPrice = 4.75
    var itemPrice_before_discount = 4.75
    var itemImageURL = "image4.jpg"
    
    var items = {
        "id": itemID,
        "name": itemName,
        "description": itemDescription,
        "price": itemPrice,
        "price_before_discount": itemPrice_before_discount,
        "imageURL": itemImageURL
    }
    
    menu.category.products.push(items);
    
    
    console.log(JSON.stringify(menu, null, 2));

The outcome of the above code is:

    {
      "category": {
        "id": "10102",
        "name": "Breakfast",
        "products": [
          {
            "id": "10101",
            "name": "Cheese Cake",
            "description": "New York Style",
            "price": 1.55,
            "price_before_discount": 1.55,
            "imageURL": "image.jpg"
          },
          {
            "id": "10102",
            "name": "Apple Pie",
            "description": "Old Fashion Home Made Pie.",
            "price": 1.75,
            "price_before_discount": 1.75,
            "imageURL": "image.jpg"
          },
          {
            "id": "10104",
            "name": "Ham and Eggs",
            "description": "With Hash Browns and Toast",
            "price": 4.75,
            "price_before_discount": 4.75,
            "imageURL": "image4.jpg"
          }
        ]
      }
    }

I am currently experiencing difficulty with adding the category node, as the data being added overrides/updates the existing category node. My query is how can I properly append the category node into its correct position.

Appreciate your help.

Answer №1

It would be beneficial to improve the structure of your code by utilizing classes. Implementing a proper data structure not only enhances code readability and comprehension but also facilitates future data modifications.

The code seems self-explanatory, but feel free to inquire if anything is unclear.

class Category {      
  constructor(id, name) {
    this.id = id;
    this.name = name;
    this.products = [];
  }
  
  addProduct(item) {
    if (item && item.type == 'product') {
      this.products.push(item);
    }
  }
}

class Product {  
  constructor(id, name, description, price_before_discount, imageURL, price) {
    this.id = id;
    this.name = name;
    this.description = description;
    this.price = price || price_before_discount;
    this.price_before_discount = price_before_discount;
    this.imageURL = imageURL;
  }
  
  get type() {
    return 'product';
  }
}

// ADDING DATA

let dessertCategory = new Category(10100, 'Dessert')
let cheeseCakeProduct = new Product(10101, 'Cheese Cake', 'New York Style', 1.55, 'image2.jpg')

dessertCategory.addProduct(cheeseCakeProduct);

let breakfastCategory = new Category(10104, 'Breakfast')
let hamAndEggsProduct = new Product(10104, 'Ham and Eggs', 'With Hash Browns and Toast.', 4.75, 'image4.jpg')

breakfastCategory.addProduct(hamAndEggsProduct);


let menu = {};

menu.categories = [];

menu.categories.push(dessertCategory);
menu.categories.push(breakfastCategory);

console.log( menu );
console.log( '----' );
console.log( JSON.stringify(menu) );

Answer №2

JSON functions as a key-value data structure, where each key must be unique. To address this issue, you can include a counter to differentiate between items within the same category.

 {
  "category1": {...},
  "category2": {...},
  ...
  }

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

Adjust the dimensions of the canvas without disrupting the existing artwork

I am currently working on a pixel art application where I am facing an issue with saving images from the canvas. The saved image appears small and pixelated when I try to resize it. I would like to resize the image to larger dimensions, but I am unsure of ...

The concept of AJAX send function and toggling button visibility

I am facing a challenge with a textarea and send button on a panel that is displayed after entering the first character. The visibility of the button is controlled by the isButtonVisible() method. Once clicked, it sends the text from the textarea using the ...

Tips for displaying text gradually when hovering over a button

Is there a way to make text appear slowly on hover of a button without it coming from the bottom to the right? I attempted using transition:all 5s;, but encountered the issue of the text moving from the bottom to the right due to improper width. Is there a ...

Formik button starts off with enabled state at the beginning

My current setup involves using Formik validation to disable a button if the validation schema is not met, specifically for a phone number input where typing alphabets results in the button being disabled. However, I encountered an issue where initially, ...

Working with newline-separated JSON in PHP

Is there a way to achieve this using PHP? I am having trouble decoding it and keep getting null values. Can anyone provide an example of how to separate each line and decode them? Check out the JSON file here: Here is some code that I have added: $jsonF ...

Tips for reducing code length in jQuery

Here's an interesting question that I've been pondering. Is there a more efficient way to optimize and condense code like the one below? Could it be achieved using functions or loops instead of having lengthy jQuery code? var panels = ["panel1", ...

No Access-Control-Allow-Origin or Parsing Error with jQuery

I am attempting to use ajax from a different server to request data from my own server as a web service. The response is a valid json generated by json_encode. {"reference":"","mobile":"","document":"","appointment":""} To avoid the 'Access Control ...

The precision of the stopwatch is questionable

Just starting out with JS and jquery, I quickly put together a stopwatch code in JS that seems to work accurately up to 10 minutes. The issue arises after the 10-minute mark where it starts falling a few seconds behind (I compared it to a digital stopwatc ...

Sending Json data to the object constructor during deserialization

Dealing with a Json file that comprises nested serialized objects can be tricky. Upon deserialization, these nested objects need to be reconstructed properly. A common way to achieve this is by using JsonConvert.DeserializeObject method: var SomeNestedObj ...

The three.js pointLight has been updated from version 67 to version 68

There appears to be a change in the interaction between a pointlight and a plane from version r.67 to r.68. I am currently studying three.js by following along with a book that is a year old. I have simplified the tutorial example to include just a plane, ...

Best practices for transferring data in node.js (unresolved)

Is it possible to pipe a file from an external server through localhost using Node.JS? (Imagine loading localhost as if it were another site like ) Here is the scenario: A PC requests http://localhost:80/highres/switch.html The Node application then ...

What exactly do the terms "index" refer to when it comes to Three js JSON attributes?

After exporting a 3D model to json from Blender, I noticed something interesting. The model appears with the "index" highlighted in yellow, as shown in this image: index is highlighted with yellow. This has sparked my curiosity - what exactly does this " ...

Utilize a CSS selector to target all deleted nodes using the MutationObserver in the HTML5 API

Is there a way to retrieve all removed nodes from the DOM that have specific classes using CSS selectors? Below is an example of how it can be done with some complexity, but is there a simpler and more general approach? new MutationObserver(mut =& ...

Does utilizing this.someFunction.bind(this) serve a purpose or is it duplicative

As I analyze someone's code, I stumbled upon the following snippet: this.device_name.changes().onValue(this.changeName.bind(this)) My interpretation so far is that onValue requires a callback function, which in this case is this.changeName.bind(this ...

Understanding the unpredictability of A-Sync in Node.js/Express: Why does it appear to operate in a non-linear fashion?

Recently, I delved into the world of Node.js/Express and encountered asynchronous calls that must complete before moving on. My code features three different endpoints that need to be hit. Considering the asynchronous nature, I attempted to structure my c ...

Implementing a filter on retrieved data from an API in a React application

I'm retrieving information from this Api After fetching the data, I need to check if the gender is Male in order to display a Male Icon. How can I perform this check on the Api data and return some HTML data like an img tag or something to show the i ...

Guide to iterating through an array within an object in Vue.js

Can someone help me with looping through data fetched from an API using a GET request in Vue.js? This is the sample response obtained: "data": { "Orders": [ { "OrderID": 1, "Ordered_Products": { ...

Encountering an HTTP 415 error due to an unsupported media type while accessing a Web API 2

I am in the process of updating an existing Web API 2 service by modifying one of its methods to accept a custom object as an additional parameter. Initially, the method only had one parameter which was a simple string extracted from the URL. However, upon ...

Node.js equivalent of scanfIs there a scanf equivalent in Node

When working with input streams in C, the scanf function is commonly used. Is there a similar method in NodeJS for achieving the same functionality? For example, here's a snippet of code in C: int n, m, i; scanf("%d", &n); for (i = 0; ...

Is it possible to hide Form elements and remove their values simultaneously?

I have implemented a script to display an additional language menu, which functions perfectly. However, I encountered an issue where if the user selects a language and then decides to remove it by clicking on "Remove", the field is hidden but the value sti ...