[Vuejs]-Replacing JSON obj with letters

0👍

Looking at your output, I think you are looking for replaceAll instead of replace.

You can have a look at it here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll

0👍

.replace() returns a new string (it does not modify the existing string)

So you would need to replace and assign back into the choices array. For Ex. :

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");

Working 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>

FYI : In JavaScript, strings are immutable – an existing string is never modified.

Leave a comment