Substituting JSON objects with alphabets

When running this code, the expected output will display the name and the choices. To clarify, I aim to substitute the values of Not effective, Neither effective nor Effective, Effective with "A", "B", and "C", respectively.

I am facing difficulty in identifying any issues or omissions within my code. It appears to function correctly only when selecting Not effective for Question 1, Neither effective nor Effective for Question 2, and Effective for Question 3. Here is the output generated when choosing Not effective for all questions: output

   Survey
        .StylesManager
        .applyTheme("defaultV2");
    
        const json = {
            pages: [
              {
                questions: [
                  {
                    type: "radiogroup",
                    name: "Question 1",
                    title: "Deliver through others.",
                    choices: [
                      "Not effective",
                      "Neither effective nor Effective",
                      "Effective"
                    ]
                  },
                  {
                    type: "radiogroup",
                    name: "Question 2",
                    title: "Understand others perspective.",
                    choices: [
                      "Not effective",
                      "Neither effective nor Effective",
                      "Effective"
                    ]
                  },
                  {
                    type: "radiogroup",
                    name: "Question 3",
                    title: "Solve complex problems.",
                    choices: [
                      "Not effective", 
                      "Neither effective nor Effective",
                      "Effective"
                    ]
                  },
                ]
              }
            ]
          };
    
    window.survey = new Survey.Model(json);
    
    survey
        .onComplete
        .add(function (sender) {
            let data = JSON.stringify(sender.data)
            data = data.replace("Not effective", "A")
            data = data.replace("Neither effective nor Effective", "B")
            data = data.replace("Effective", "C")
    
            var obj = JSON.parse(data)
    
            document
                .querySelector('#surveyResult')
                .textContent = "Result JSON:\n" + JSON.stringify(obj, null, 3);
    
        });
    
    var app = new Vue({
        el: '#surveyElement',
        data: {
            survey: survey
        }
    });

Answer №2

When you use .replace(), it returns a new string instead of modifying the existing one.

Therefore, you must replace and reassign the values back into the choices array. For example: :

choices[0] = choices[0].replace("Not effective", "A");
choices[1] = choices[1].replace("Neither effective nor Effective", "B");
choices[2] = choices[2].replace("Effective", "C");

View Demo :

const json = {
  pages: [
    {
      questions: [
        {
          type: "radiogroup",
          name: "Question 1",
          title: "Deliver through others.",
          choices: [
            "Not effective",
            "Neither effective nor Effective",
            "Effective"
          ]
        },
        {
          type: "radiogroup",
          name: "Question 2",
          title: "Understand others perspective.",
          choices: [
            "Not effective",
            "Neither effective nor Effective",
            "Effective"
          ]
        },
        {
          type: "radiogroup",
          name: "Question 3",
          title: "Solve complex problems.",
          choices: [
            "Not effective", 
            "Neither effective nor Effective",
            "Effective"
          ]
        },
      ]
    }
  ]
};

new Vue({
  el: '#app',
  data: {
    questions: json.pages[0].questions,
    updatedData: []
  },
  mounted() {
    this.updatedData = this.questions.map((obj) => {
        obj.choices[0] = obj.choices[0].replace("Not effective", "A");
      obj.choices[1] = obj.choices[1].replace("Neither effective nor Effective", "B");
      obj.choices[2] = obj.choices[2].replace("Effective", "C");
      return obj;
    });
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div v-for="(question, index) in updatedData" :key="index">
    <p v-for="choice in question.choices" :key="choice">
      {{ choice}}
    </p>
  </div>
</div>

Just so you know, In JavaScript, strings are immutable - meaning an existing string is never modified.

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

Error in calculation of $.post function in JQuery

I am facing an issue with my file delete.php, which contains the following code: <?php $folder = "./fak/"; $filename = $_POST['name']; unlink($folder.$filename); ?> Additionally, I have an index.html file with the below code: <html ...

Deciphering the LocalDate and nested object array in an AJAX response

Seeking assistance, looking for solutions to two problems. Firstly, how can I display LocalDate in an ajax response? And secondly, how do I iterate over a list of Custom objects received in the ajax response? I am passing a List of Custom Objects and Loca ...

Inquiries about ngshow and the scope concept

I have a question about using AngularJS. I have multiple sections and only want to display one at a time using <section ng-show="section6_us"> </section> and <section ng-show="section7_us"> </section>. My scope has many variables. ...

How can you determine if a domain belongs to Shopify when given a list of 98000 domain names using Node.js?

Is there a way to determine if a domain is operating on the Shopify e-commerce platform? I have been searching extensively but haven't found a reliable method. I possess an array containing 98,000 domain names and I am interested in utilizing node.js ...

Element cannot be located following the addition of a className in the HTML document

When manually adding id, test-id or classname in an HTML file, it's important to note that Cypress may have trouble finding the element. For example, I have included 'Classname' here just for demonstration purposes. https://i.stack.imgur.co ...

What is the Typescript definition of a module that acts as a function and includes namespaces?

I'm currently working on creating a *.d.ts file for the react-grid-layout library. The library's index.js file reveals that it exports a function - ReactGridLayout, which is a subclass of React.Component: // react-grid-layout/index.js module.exp ...

Leveraging the power of Ajax and Nodejs to dynamically refresh content on a webpage

I'm currently working on creating a loop to refresh a webpage every 30 seconds, but I'm facing some challenges with making an ajax call using the setInterval function. Below is a snippet of my server-side code: var app = express() app.get(' ...

Using a .NET Web-API controller variable as a parameter in a JavaScript function

I am looking to send a "variable" from the controller to a JavaScript function. The code I have implemented is as below: <div ng-controller="faqController"> <div ng-repeat="c in categories"> <h2 onclick="toggle_visibility(&apos ...

What could be causing the dysfunction of the jQuery class adding function?

I'm new to using jQuery and I'm trying to add a class to the 'a' tag when the 'li' tag is clicked. However, it doesn't seem to be working as expected. $('.nav-item').click( function() { $(".nav-item a").re ...

When trying to manually trigger the firing of the autocomplete function to get a place using Google API

My goal is to retrieve the data from autocomplete.getPlace() when triggering this event manually. Essentially, I have a function that captures the user's location in Lat/Lng format, and afterward, I aim to access other useful data using getPlace() su ...

The outcome of a MySQL query involving JSON_OBJECT() is a string value

I have crafted a query that extracts posts from a table and includes information about each post's author: SELECT post.id, post.text, post.datetime, JSON_OBJECT( 'username', user.username, 'firstName', user.firstName, 'last ...

Which approach yields better performance: setting all dom events simultaneously, or incrementally?

Is it more effective to attach event listeners permanently or only when needed? For example, consider a scenario where you have a dropdown menu in your HTML that opens when clicked. Within this menu, there is a close button that closes the menu upon click ...

Guide for inserting personalized buttons onto a map with the Bing Maps 6.3 Ajax Control

Looking to enhance a Bing Map with custom buttons for more interactive functionality? I'm interested in creating a custom dashboard on the map that would allow users to toggle different information or colors displayed on specific pins or polygons by s ...

Display only a loading image with a see-through background after submitting the page

After submitting the page, I would like to display a loading image in the middle of the page with a transparent background. The current styling code I have used is as follows: #loading { position: fixed; top: 50%; left: 50%; z-index: 1104; ...

How to filter jQuery DataTables by column using comparison operators

Recently, I've been utilizing the amazing DataTables jQuery plugin along with the filter plug in. But now, I find myself pondering if there's a way to filter table columns by row using a comparison operator (such as '<', '>', ...

showing a fading-in effect after a successful AJAX post

Maybe a simple question, but I've been struggling to make this work for quite some time now. Despite trying various solutions from stackoverflow, I can't seem to get it right. Perhaps fresh eyes could help me figure out how to achieve this. My g ...

The Jenkins build on a specific branch is encountering issues with path exporting, causing it to fail

I have a set of files related to a new feature that I am trying to deploy through Jenkins. I have successfully deployed other branches in the past, but I am encountering difficulties with a specific branch. I believe the problem may be related to the use ...

The Vue instance methods provide a way to access and manipulate formatted properties

I am looking to implement a method that will generate the appropriate email format to be used as the href value in an anchor tag. This method should return the formatted string in the following format: "mailto:[email protected]". var facultyInformat ...

Send visitors to a different page for a brief 10-second interlude before bringing them back to where they started

Is there a way to create a temporary redirect for users to an ad page and then automatically return them to their desired page after 10 seconds? I have limited knowledge of PHP and Java, so I would appreciate any guidance or complete redirect code that co ...

Tips for validating the input type "password"

Below is the Jquery Script that I am using: $(document).ready(function(){ $("#myForm").validate({ rules: { username: { required:true }, password: { required:true ...