Home > Blockchain >  Building JSON files in Javascript - Problem in append data
Building JSON files in Javascript - Problem in append data

Time:04-24

My objective is to create a JSON dataset as follows: 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 above code results are:

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

The problem I am having is adding the category node, currently the data to be appended overlays/updates the previous category node.

My question is how to add/append the category node in the proper position.

Thank you.

CodePudding user response:

I think you need to structure your code a bit more, by using classes. It's just soo much easier to handle data if you set up a proper data structure, both when it comes to reading/understanding the code but also modifying the data in the future.

I think the code is self-explanatory, but do ask if something 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) );

CodePudding user response:

json is like key, value data structure, you can not have 2 item with the same key. For this problem you can add number like counter to category

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