Working with Vue.js: Utilizing computed properties to iterate through a JSON data structure and generate a new

This is a computed property in Vue.js:

shopCart() {
      var scart = [],
        group,
        node;
      scart.push({
        payMethod: 0,
        transactionReference: "",
        RoomNumber: 0,
        addressId: 0,
        deliveryMinutes: 0,
        comment: "",
        posList: [],
      });
      for (var x = 0; x < this.items.length; x++) {
        group = this.items[x].selectedOptions;
        scart[0].posList.push({
          articleId: this.items[x].id,
          quantity: this.items[x].quantity,
          singlePrice: this.items[x].price,
          variantList: [],
          parent: true,
          name: this.items[x].name,
        });
        for (var y = 0; y < group.length; y++) {
          node = group[y].options;
          for (var z = 0; z < node.length; z++) {
            scart[0].posList[0].variantList += node[z].id + ",";
          }
        }
      }
      scart = scart.map(function (e) {
        return JSON.stringify(e);
      });
      scart = scart.join(",");
      return scart;
    },

It generates the following object:

{
  "payMethod": 0,
  "transactionReference": "",
  "RoomNumber": 0,
  "addressId": 0,
  "deliveryMinutes": 0,
  "comment": "",
  "posList": [
    {
      "articleId": 20001,
      "quantity": 1,
      "singlePrice": 8.99,
      "variantList": "2001,4001,5001,2003,4003,",
      "parent": true,
      "name": "Fisch Filet"
    },
    {
      "articleId": 20002,
      "quantity": 1,
      "singlePrice": 8.99,
      "variantList": "",
      "parent": true,
      "name": "Cheese Burger"
    }
  ]
}

I am looking to achieve this format:

{
  "payMethod": 0,
  "transactionReference": "",
  "RoomNumber": 0,
  "addressId": 0,
  "deliveryMinutes": 0,
  "comment": "",
  "posList": [
    {
      "articleId": 20001,
      "quantity": 1,
      "singlePrice": 8.99,
      "variantList": "2001,4001,5001,",
      "parent": true,
      "name": "Fisch Filet"
    },
    {
      "articleId": 20002,
      "quantity": 1,
      "singlePrice": 8.99,
      "variantList": "2003,4003,",
      "parent": true,
      "name": "Cheese Burger"
    }
  ]
}

The issue lies with the nested loop writing the string only into the first occurrence of "variantList". I need help figuring out how to handle the occurrence of "variantList' in the previous loop correctly. Any guidance would be greatly appreciated.

Items.json:

[
  {
    "id": 20001,
    "name": "Fisch Filet",
    "quantity": 1,
    "selectedOptions": [
      {
        "id": 1,
        "name": "Beilage",
        "options": [
          {
            "id": 2001,
            "optionQuantity": 1
          }
        ]
      },
      {
        "id": 2,
        "name": "Salate",
        "options": [
          {
            "id": 4001,
            "optionQuantity": 1
          }
        ]
      },
      {
        "id": 3,
        "name": "Ketchup/Mayo",
        "options": [
          {
            "id": 5001,
            "optionQuantity": 1
          }
        ]
      }
    ]
  },
  {
    "id": 20002,
    "name": "Cheese Burger",
    "quantity": 1,
    "selectedOptions": [
      {
        "id": 1,
        "name": "Beilage",
        "options": [
          {
            "id": 2003,
            "optionQuantity": 1
          }
        ]
      },
      {
        "id": 2,
        "name": "Salate",
        "options": [
          {
            "id": 4003,
            "optionQuantity": 1
          }
        ]
      }
    ]
  }
]

Answer №1

After carefully considering the input items and desired outcome, I propose a solution that involves utilizing the map method:

updateShoppingCart() {
      var cartItems = [],
        group,
        element;
      cartItems.push({
        paymentType: 0,
        referenceNumber: "",
        RoomID: 0,
        addressIdentifier: 0,
        deliveryTime: 0,
        notes: "",
        productList: this.items.map(item=>{
                       item={
                       ID: item.id,
                         quantity: item.quantity,
                         pricePerItem:item.price,
                                            
                      variationList:item.selectedOptions.map(opt=>opt.options[0].id).join(),
                         isParent: true,
                         itemName: item.name,
                       }; 
                     return item;
                   }) ,
      });

return cartItems;

}

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

Working with JSON containing nested arrays in PHP without using square brackets

While browsing through StackOverflow, I noticed that many questions were similar to mine but none provided a complete answer. To test a POST request in an Android app, I came across an example that utilized the following test API: Upon accessing this API ...

Guide to dynamically adjusting the input type

Within my Vue page, there are three distinct input fields: <input id="id" class="flex-grow bg-white p-4 text-sm items-center focus:outline-none" type="text" name="id" v-model="id" placeholder ...

Adjust the dimensions of input tag depending on the length of content in Angular

Is there a way to dynamically set the size of the input tag in my HTML based on the length of the ng-model value? I attempted this approach: <span>Node Path: <input for="nodeName" type="text" ng-model="nodePath" size="{{nodePath.length()}}"ng- ...

Improving conditional rendering in Mui <Cards> component by fixing state behavior

I have a situation where I want to display a Floating Action Button inside each Mui card when hovered over. However, I'm running into an issue with the hover state affecting all cards instead of just the one being interacted with. How can I ensure tha ...

Iterating over a JSON object with an embedded index in Angular using ng-repeat

Here is the structure of a JSON object: { "0": { "Order_Id": "100000001", "prodct_Status": "Pending", "Price": "8.0000", "date_created": "Jun 4, 2014 7:55:42 AM", "Shipping_Address": "vbccv", "Region": ...

the `req.body` method fetches an object with a property named `json

Having an issue with accessing data from req.body in my form created with JS { 'object Object': '' } //when using JSON.stringify: { '{"A":"a","B":"b","C":"c"}': &apo ...

I am experiencing issues with my $ajax request

After running the code snippet below: websiteUrl= "http://192.168.2.171/LoginAuthentication"; $.ajax({ url: 'websiteUrl', type: 'GET', success: function(response) { var title = $(response.responseText).find('a. ...

Creating a simulation of a ReactJS form tag using TestUtils does not activate the `onSubmit` event

When attempting to simulate the onSubmit event on the form tag using Sinon to spy on the method, it appears that the method being spied on is not called at all. For reference, here's a JSFiddle. ...

Callbacks in Laika tests go untriggered

Meteor.collection.insert() allows for the use of a callback as one of its arguments. To demonstrate, you can start a new Meteor project and execute the following code in the browser's console. my_collection = new Meteor.Collection("myCollection"); my ...

Using JQuery to implement custom validation on a text field is an effective way

How can I validate a text field using Regex and create my own validation rule for starting with "com."? Can you provide me with an example of how to do this? I want the text field to only accept values that start with com. <input id="appPackage" name=" ...

What causes req.body to be null after using event.preventDefault() in conjunction with fetch api, express, and node.js?

Is there a way to submit a form without causing the page to reload and still retrieve an object from MongoDB using server side scripts? I've tried preventing the default behavior of the form with an event handler to avoid the page refresh, but this ca ...

Typescript throws an error indicating that the "this" object in Vue methods may be undefined, displaying error code TS2532

As a beginner in question writing, I apologize if my wording is not clear. The issue at hand: I am working on a Vue application with TypeScript. export default { methods: { setProgram: (program: Program)=>{ this.program = progra ...

Tips on how to properly display the date in v-Calendar

I'm struggling to format the date output from the v-calendar. Currently, it appears like: Fri Jul 31 2020 00:00:00 GMT+0200 (utc summertime) However, I would like it to display as 2020-07-28. I have searched through the documentation but couldn' ...

Execute Function after Gridview Sorting

While working on a gridview within an update panel, I encountered a scenario where the gridview successfully resorts itself upon clicking on the column header. However, post-sorting, I wish to execute a JavaScript function named MyScript. Any suggestions ...

Is there a way to reduce the excessive bottom margin on Twitter embeds?

Is there a way to adjust the Twitter embed code for tweets so they don't have a large margin at the bottom? Here is an example of the standard Twitter embed code: <blockquote class="twitter-tweet"><p>@<a href="https://twitter.com/gami ...

During rendering, the instance attempts to reference the "handleSelect" property or method which is not defined

I've incorporated the Element-UI NavMenu component into my web application to create a navigation bar using Vue.JS with TypeScript. In order to achieve this, I have created a Vue component within a directory called "navBar," which contains the follow ...

Switching the border of a div that holds a radio button upon being selected

I have a piece of code that I use to select a radio button when clicking anywhere within a div, which represents a product photo. To make it clear for the customer, I want to add a border around the selected product. Here is the initial code: <script t ...

AngularJS SmartyUI position not dynamically updating on SmartyStreets plugin

In my angularJS application, I am utilizing SmartyStreets' LiveAddress for address validation and autofilling two fields in a form. After the user submits the form, a message (either success or failure) is displayed in a div above the form. However, t ...

After making 5 Ajax get requests, there is no response being received

Currently, I'm facing an issue when trying to retrieve information from the MongoDB server to the frontend using an AJAX GET request. Everything works smoothly until I attempt to call the JavaScript function multiple times. Strangely, if I call the fu ...

Utilizing model associations in Sails.js to populate an array

I am currently using "sails": "~0.10.0-rc5", "sails-mongo": "^0.10.0-rc3". I have two models: Invoice and Item. Invoice model Invoice: { name: 'sample 1', items: [1,2] // 1,2 are the ids of the Item model } Item model Item { id: 1 ...