Adding JSON to an existing object in JavaScript involves using the `JSON

I'm facing a challenge with integrating JSON into existing objects using Vue.js. Currently, I have a function that calculates variants successfully, but I need to modify them to ensure accurate data is sent to my Laravel backend.

Here is what my array looks like (used for variant calculation):

"attributes":[
      {
         "title":{
            "text":"Size",
            "value":"1"
         },
         "values":[
            "Red",
            "Green"
         ]
      },
      {
         "title":{
            "text":"Color",
            "value":"2"
         },
         "values":[
            "X",
            "M"
         ]
      }
   ]

And this is how the calculation is done:

addVariant: function () {
            const parts = this.form.attributes.map(attribute => attribute.values);
            const combinations = parts.reduce((a, b) => a.reduce((r, v) => r.concat(b.map(w => [].concat(v, w))), []));
            
            this.form.variants = combinations;
        },

The current output:

"variants":[
      [
         "Red",
         "X"
      ],
      [
         "Red",
         "M"
      ],
      [
         "Green",
         "X"
      ],
      [
         "Green",
         "M"
      ]
   ]

However, I need the variants to be structured as follows:

"variants":[
        {
            "title": "Red/M",
            "slug": "prooooo",
            "options": [
                {
                    "key": "Color",
                    "value": "Red"
                },
                {
                    "key": "Size",
                    "value": "M"
                }
            ]
        },
        {
            "title": "Red/X",
            "slug": "prooooo",
            "options": [
                {
                    "key": "Color",
                    "value": "Red"
                },
                {
                    "key": "Size",
                    "value": "X"
                }
            ]
        }

The title field needs to be calculated based on options.values. How can I transform the JSON structure to match the desired format?

Any suggestions on accomplishing this? Thanks in advance!

Answer №1

After a thorough examination, it appears that the missing elements needed to generate the final result are the key attributes within the options arrays, specifically located in the initial attributes array under the text attribute of the title object.

To address this issue, the initial modification involves adjusting the creation process of the parts variable: instead of directly returning the attribute.values, the values are now mapped over to retain the associated attribute.title.text.

In parallel, the keys for the resulting object are aligned with the structure of the options object in the desired output.

const parts = this.form.attributes.map((attribute) =>
  attribute.values.map((value) => {
    // `options` objects consist of `value` and `key` properties
    return { value, key: attribute.title.text };
  })
);

The logic pertaining to the combinations remains unchanged.

Subsequently, an iteration process is conducted on the combinations to formulate the new array named variants.

let variants = [];

for (const combination of combinations) {
  variants.push({
    // Utilize template strings for constructing the new title
    title: `${combination[0].value}/${combination[1].value}`,
    slug: "...desired value",
    // The variable 'combination' already adheres to the structure required for 'options'
    options: combination
  });
}

The eventual implementation will exhibit a configuration resembling the following:

addVariant: function () {
  const parts = this.form.attributes.map((attribute) =>
    attribute.values.map((value) => {
      return { value, key: attribute.title.text };
    })
  );

  const combinations = parts.reduce((a, b) =>
    a.reduce((r, v) => r.concat(b.map((w) => [].concat(v, w))), [])
  );

  let variants = [];

  for (const combination of combinations) {
    variants.push({
      title: `${combination[0].value}/${combination[1].value}`,
      slug: "...desired value",
      options: combination,
    });
  }

  this.variants = variants;
}

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

Adding a file filter in Kendo v2016 is a simple process that can greatly enhance

I'm exploring how to implement a file filter in Kendo.Mvc.UI.FileUpload. I've come across some examples online that utilize a method called 'select', but it seems that the current version of Kendo I'm using doesn't have this m ...

Unit testing Angular SVG to retrieve the SVGLengthList

Hello everybody! I am in need of some assistance regarding SVG. I am currently working on writing unit tests and I need to add an object with the type SVGLengthList to a method. I have gone through the documentation provided by W3, however, I am unsure of ...

Creating a personalized <select> filter in Angular.js with two different JSON choices

I am working with a Q&A JSON feed that includes the following: "questions": [ { "answer": "Ea et non sunt dolore nulla commodo esse laborum ipsum minim non.", "id": 0, "poster": "Chelsea Vang", "question": "Ex ex elit cu ...

Modifying a property name in a JSON object for each descendant element in a recursive manner

I have the following JSON object: myJsonObj = { "name":"Laptop", "type":"hardware computer laptop", "forward":[ { "name":"Depends On", "forward":[ { "name":"test asset 1", ...

What is causing the TypeError in Discord.js when trying to read the 'voice' property? Any help troubleshooting this issue would be greatly appreciated

Hey everyone, I'm having an issue with my play.js file that I obtained from a Source Bin. If anyone could provide some assistance, it would be greatly appreciated. const ytdl = require("ytdl-core"); const ytSearch = require("yt-search"); //Global que ...

Creating an array to store multiple ID values within a variable

const idArray = $scope.rep.Selected.id; I am working with this piece of code. I am wondering, if I have multiple ids in the $scope...Selected.id and then execute this (code), will all these ids be placed in separate arrays or combined into one array? ...

I am attempting to display films within a watchlist module, however it is not allowing me to do so

I have developed a small movie database and need to showcase movies on my watchlist. While I am able to search for movies, adding them to my watchlist is only reflected in the Homescreen component and not in the WatchList component. This is the current s ...

Sharing data between Vue components

Recently delved into the world of Vue.js and could use some guidance. I've got two components that are not directly connected as parent and child. I attempted passing a variable between the two using "props," but it didn't work out as planned. ...

Trouble arises with MySQL query in PHP/jQuery setup

I am currently in the process of developing a user panel where users can change their first and last names. Everything seems to be working fine with the $ajax form handling, as I can use console.log(data) and see {fname: "Damian", lname: "Doman", id: "20" ...

Jquery validation is ineffective when it fails to validate

I have implemented real-time jQuery validation for names. It functions correctly in real-time, however, when I attempt to submit the form, it still submits the value even after displaying an error message. Below is the code snippet for the validation: $ ...

Tips for animating a nested array using jQuery

I have a border that is 9x9 with lines, columns, and squares, similar to a Sudoku border. I want to animate it, but I encountered some issues when trying to run multiple animations simultaneously. To solve this problem, I decided to animate one array of el ...

How to pass a PHP variable to JavaScript and ensure that the echo statement reflects any changes in the PHP variable

I am currently developing a script that dynamically generates a web page using data from my database. To achieve this, I have implemented a JavaScript function that is called when the page loads and whenever there is an update required. Initially, I succe ...

Error encountered when attempting to initiate a second screenshare on Chrome due to an invalid state

I am interested in utilizing Screensharing in Chrome. After following a guide and creating an extension to access the deviceId for getUserMedia, I was able to successfully start streaming my screen. However, when I attempted to stop the stream using the pr ...

Dynamic color updates for Angular list items on click

Utilizing angularjs, I have two lists. When the first one is clicked, the value will be pushed into another scope and bound to the second list. Now, my goal is to change the color of the values moved from the first list to the second list in list1. Check ...

Contrast between a pair of methods for submitting a request in an Express application

I am curious about the contrast in making requests using two different approaches within an Express application. Firstly, I encountered this code snippet in a repository: http.get(options, res => { res.on('data', data => { r ...

Converting a JSON array into a table using AngularJS

Here is the structure of my JSON data: [{"Name":["A","B","C","D","E","F"], "Age":["20","30","40","50","55","60"], "Gender":["M","M","F","M","Unknown","Unknown"]}] I am looking to create an AngularJS table that resembles the following format: Name Age ...

Can you tell me how to display the currently utilized Node.js version and path within npm?

I’m encountering a similar issue to the one discussed in this Stackoverflow thread: SyntaxError: Use of const in strict mode?. However, my problem arises when attempting to install Flux. I followed the steps outlined in the linked Stackoverflow question ...

Finding the Right Path: Unraveling the Ember Way

Within my application, I have a requirement for the user to refrain from using the browser's back button once they reach the last page. To address this, I have implemented a method to update the existing url with the current page's url, thereby e ...

Rotation snapping feature 'control.setRotationSnap' in TransformControls.js (Three.js) is not functioning properly

Attempting to utilize the functionality of "control.setRotationSnap" from the script "TransformControls.js", but unfortunately, it is not working as expected. After conducting some research, I came across a forum post suggesting that the code might not be ...

Navigate to the most recent entry in the array while using ng-repeat

I am attempting to implement scrolling to the last added entry within an ngRepeat directive. After researching related questions on Stack Overflow, such as #1 and #2, I still cannot find a solution to my problem. The code is straightforward. When a user ...