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

How can I rectify the varying vulnerabilities that arise from npm installation?

After running npm audit, I encountered an error related to Uncontrolled Resource Consumption in firebase. Is there a solution available? The issue can be fixed using `npm audit fix --force`. This will install <a href="/cdn-cgi/l/email-protection" clas ...

Encountering an issue in a Next.js application while building it, where an error is triggered because the property 'protocol' of 'window.location' cannot be destructured due to being undefined

While building my nextjs application, I encountered the following error. My setup uses typescript for building purposes, although I am only using JavaScript. Build error occurred: TypeError: Cannot destructure property 'protocol' of 'window ...

The steps to properly load "child.vue" into the correct position within "parent.vue" are as follows

Currently I am developing a single page web application using Vue.js. This app consists of 4 "page.vue" files, each with a right and left child .vue component nested inside. For instance, the Page1.vue file is structured as follows (omitting style and scr ...

Tips for automatically setting focus to the following cell after inserting a new row in AngularJS

Transitioning from the Knockout world to Angular, I am facing an issue with a key-press event for tab. Whenever I add a new row in the table, the focus shifts to the information icon in the URI bar instead of the next cell in the newly created row. I belie ...

Understanding how the context of an Angular2 component interacts within a jQuery timepicker method

Scenario: I am developing a time picker component for Angular 2. I need to pass values from Angular 2 Components to the jQuery timepicker in order to set parameters like minTime and maxTime. Below is the code snippet: export class TimePicker{ @Input() ...

Using the $lookup aggregation stage to $group a nested array in MongoDB

I'm working with a Product Schema that is partially built using mongoose. Here's a snippet: attributes: [ { set: { ref: 'AttributeSet', type: Schema.Types.ObjectId }, items: [ ...

Adjust the displayed HTML Tag within a Vue Component to add variety

Is it possible to allow a user to choose which HTML tag will be rendered in a VueJS Component? For example, consider <my-component>Some Text</my-component>. I would like to create a property called "tag" that determines the HTML tag to render ...

Loading identical code in two different div elements

I am in the process of designing a comprehensive resource database featuring a side-scrolling container. Once a user clicks on a thumbnail within the container, the contents of a corresponding div will fade in and display specific category content. Each di ...

Creating a textbox with pre-filled content

Seeking assistance with a Java compiler app I am developing through phonegap. Need help setting the default Java Class name in a textarea without it disappearing. This is what I have: <div> <label for="source">Source Code:</label> ...

Troubleshooting issues with filtering two MongoDB arrays in ES6 and finding a solution

I have a scenario where I am requesting two arrays of objectIDs from MongoDB, and then attempting to identify the differences between the two arrays. In addition, I am passing these arrays through express middleware using res.locals. Below is the code sn ...

Expanding a responsive HTML background image using Javascript

I've spent countless hours grappling with this code, attempting to dynamically resize the background of HTML based on the browser window size using JavaScript. Here's what I have so far (I'm using Firefox for this): GM_addStyle('body ...

Distinguishing Routes for Administrators and non-Administrators in Laravel

I am currently developing a Single Page Application (SPA) using Laravel and Vue. My goal is to have two separate routes for admin and non-admin users, as shown below. // For Admin Route::any('admin/{any}', static function () { return view(&a ...

When executing an $http get request in Angular, a promise is

After implementing this code in my service and noticing that it works, I have a question. Since $http.get() returns a promise which executes asynchronously, I am confused about why I need to use deffered.resolve(res.data) to return data in my service. Yo ...

JavaScript code that loads a copied mesh object using three.js

Currently using three.js version r59, encountering difficulties when attempting to duplicate a loaded model. The goal is to create multiple models through looping, with the plan to apply textures at a later stage. for (var i=0; i<5-1; i++){ va ...

Accessing User Input Data with JQuery

Can someone help me figure out how to store the input value from a Materialize select form in HTML using a variable in javascript/jquery? Here is the HTML code for the form: <div class="input-field col s12"> <select> <option va ...

"Encountered a syntax error while attempting to reference an attribute on an empty object

> "[object Number]" === Object.prototype.toString.call(1) // #1 < true > "[object Number]" === {}.toString.call(1) // #2 < true > {}.toString.call(1) === "[object Number]" // #3 < SyntaxError: Unexpected token ...

What is preventing my function from retrieving data from the JSON File?

Exploring the realm of JSON file manipulation, I am delving into how it functions. Equipped with a JSON file attached to my document and a function sharing the same name as my object in the JSON file. However, despite all efforts, the data is not being dis ...

Leveraging vuex in conjunction with typescript allows for efficient management of state in namespace modules,

I am currently integrating vuex with typescript and namespaces module in my project. Within this setup, I have two distinct modules: "UserProfile" and "Trips". So far, everything is functioning smoothly within the confines of each module. However, I have ...

Implement a specific focus() method on a reference element that is being iterated through using v

My objective is to have the button hidden and the corresponding input displayed and focused when the button is clicked. let tagIdBeingEdited = ref(0) let buttons = ref([]) let inputs = ref([]) async function toggleTagInput(id:number, index:number ) { ...

jQuery class toggle malfunction

I have a series of list items with specific behavior when clicked: Clicking a list item will select it and add the class .selected If another list item is clicked, the previously selected item becomes unselected while the new one becomes selected If a se ...