What is the method for generating a JSON file similar to this one when I provide input?

How can I align the cart_items to meet my expectations? That's all I want. My only problem is that I just want to make my cart_items look like this. I hope you can help me, thanks. Did I use the wrong method? Also, I want to include the qty inside the cart_items.

This is what I expect:

"cart": [
{
  "id": 1,
  "date": "12/10/2020",
  "store": {
    "id": 1,
    "name": "Dirumah Aja",
    "promo": 1
  },
  "cart_items": [
    {
      "id": 1,
      "product": {
        "id": 1,
        "name": "Bakso Urat",
        "price": 10000,
        "promo": {
          "nama": "promo"
        }
      },
      "qty": 5
    }
  ]
}
]

And this is what I currently have:

"cart": [
{
      "cart_items": {
        "name": "Steak Sapi Impor",
        "price": "38000",
        "stock": "4",
        "image": "https://firebasestorage.googleapis.com/v0/b/francise-fb70a.appspot.com/o/steak.jpg?alt=media&token=46e0d769-96d3-440f-8edb-5fce2481ace0",
        "promo": 3,
        "id": 8,
        "qty": 1
      },
      "store": {
        "name": "Amanda Foods Store",
        "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="244549454a404564424b4b4... blah blah...

This represents my current data:

data() {
        return {
            promo_id: [],
            promo_partner: [],
            products: {},
            qty: 1,
            cart_items: [
                {}
            ]
        };

This is how I'm handling it in my method:

addToCart() {
            const date = (new Date()).toString().split(' ').splice(1,4).join(' ')

            this.products.cart_items = this.product;
            this.products.cart_items.qty = this.qty;
            this.products.store = this.partner;
            this.products.date_order = date;

            console.log(this.cart_items)

            axios
                .post("http://localhost:3000/cart/", this.products)
                .then(() => {
                    swal("Belanja Berhasil!", {
                        icon: "success",
                    });
                })
                .catch((error) => console.log(error));
        }


    }

Answer №1

To insert elements into an array, utilize the .push() method. Be cautious not to overwrite the entire array with this.product.

If the cart_items in this.products is null, make sure to initialize it by setting it as an empty array.
this.products.cart_items.push({id: this.product.id, product: this.product, qty: this.qty});

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

Trouble with JavaScript confirm's OK button functionality in Internet Explorer 11

Having trouble with the OK button functionality on a JavaScript confirm popup in IE11. For one user, clicking OK doesn't work - nothing happens. It works for most other users though. Normally, clicking OK should close the popup and trigger the event h ...

Retrieve a specific value from an array within Firestore

I am facing an issue where I can only retrieve the values I need from the array by adding a specific string like "اقلام" or "سبورة". However, I want the value to be passed as a prop from another component or screen. Is there a way to resolve this ...

Angular 4 Observables: Triggered Twice Due to Successive Subscribers

Encountering a peculiar issue with Angular 4 Observables. Implemented a ServiceProxy.ts to manage all HTTP calls for the application. @Injectable() export class ServiceProxy { private base_url = 'https://localhost:8443'; ...

Refreshing a Variable's Value in NODE.JS

After much struggle, I've come to the realization that I may have to seek help from the experts on 'StackOverflow' for this issue. Here is my code that continues to baffle me: var express = require('express'), fs = require(&ap ...

Analyzing the interaction of AngularJS across different pages

I am currently working on an Angular application that consists of a login page and a landing page. My goal is to create a Protractor assertion that can verify the successful login and ensure that the landing page displays correct content. The login proces ...

Implementing lazy loading of API data in Flutter through scrolling

I have developed an API that retrieves product data from the database, shown in the following format: [ { "id": 1, "product_name": "Name1", "color": "red" }, { "id": 2, "product_name": "Name2", "color": "green" }, { "id": 3 ...

Is there a way to conceal form fields for city and state until the zip code is provided?

Is there a way to only display the city and state form fields after the zip field has been filled out? I have a geo-based program that automatically fills in the city and state based on the zip code entered, but I want to hide these fields until the data ...

Set a background image URL for a specific division inside a template

I have a drawPlaceDetails function that populates an HTML template with values. The getPhotoURL() function retrieves a URL link to an image, which I am trying to assign to the background-image property. However, the div remains empty without displaying the ...

No options displayed in AngularJS select2 dropdown

I have implemented select2 in my code following the instructions provided at https://github.com/angular-ui/ui-select2 <div ng-controller="sampleController> <select ui-select2 ng-model="select2" data-placeholder="Pick a number"> < ...

What is the best way to arrange objects in an array by date using Angular 4?

My array of objects is structured like this : this.filteredData = [ {'id': 1, 'date': '04-05-2018'}, {'id': 2, 'date': '29-03-2018'}, {'id': 3, 'date': '03-04 ...

What is the best way to save the user's response in an array for comparison with the correct answer?

Here's the concept behind how the quiz is designed to function: As the user enters their answer, it will be stored in an array for comparison with the correct answers stored in another array. var input = require("read_line-sync"); class Multiple_cho ...

How can I make a div overflow outside of a ul container when hovering over it?

Is there a way to make an arbitrary div nested within a ul overflow outside of the ul, even if the ul has a set width of 160px and overflow-y: hidden? The reason for setting it to overflow-y: hidden is because I need the list to be scrollable. Here is the ...

ng-model causing simultaneous changes to all selects

Check out this jsfiddle link Hello there, I'm encountering an issue with my application. I need to create multiple dropdowns using ng-repeat and have them all populated with the same options. The problem arises when one dropdown is changed, all ot ...

At times, Nuxt.js Oauth can lead to a complete webpage crash

I encountered an issue with my Nuxt.js application that uses the Nuxt/auth module. While everything works smoothly in web browsers, sometimes the application crashes when accessed through a mobile browser. The app becomes unresponsive, without any API call ...

Error Occurred: Angular View Not Loading

I created a new file named new.html to test navigation, but when I load the page View1.html should appear, instead I see a blank page. Below is the content of my new.html: <!DOCTYPE html> <html data-ng-app="demoApp"> <head> ...

Generate a JSON formatted string organized by calendar year using the data retrieved from a MySQL query

For my project, I have a database table named events in MySQL. My goal is to retrieve specific data from this table in JSON format. id event 1 2010-01-01 00:00:00 2 2010-02-02 00:00:00 4 2011-01-04 00:00:00 5 2012-01-30 00:00:00 6 201 ...

Gatsby's own domain and absolute links: the perfect pair

My goal is to establish a direct link to files (such as images and downloads) in my static directory. During development, the link should be http://localhost/myimage.jpg, and once deployed, it needs to switch to https://www.example.com/myimage.jpg. Is the ...

My jQuery Ajax seems to have a glitch, can someone help me figure out

Looking for some help with this HTML code: <section id="login"> <form> <input type="text" name="username" size="10" placeholder="username" /> <input type="password" name="password" size="10" placeholder="password" ...

Guide on invoking a method from a class in a different file

Seeking a solution to a task involves calling a function from a different file within a class. Here's what I am trying to achieve: file1 export class Example { constructor() { ... } myCustomFunction = () => { ... } } file2 impor ...

Dividing a string by a specified array element in Javascript

Given a string "asdlfjsahdkljahskl" and an array [1,2,3,1,7,2,1,2], the final output should be a, sd, lfj, s, ahdklja, hs, kl. I'm able to split the string, but I'm unsure how to compare the string and cut it according to the given array. Here& ...