Learn how to easily convert a string to an Object in Vue by utilizing Json.parse

My goal is to convert the input value from the input element into an Object

When I use JSON.parse() to convert the internData value, it doesn't turn the string into an Object as expected.

Interestingly, performing the same operation in the browser console gives me the correct outcome.

let data = "[1,2,3,4]";

JSON.parse(datas)
(4) [1, 2, 3, 4]

typeof z
'object'

I wonder what I might be missing here?

new Vue({
  el: "#app",
  data() {
    return {
      datatype: "foo",
      internData: "[1, 2, 3]",
    };
  },

  methods: {
    transformData() {
      //
      //
      JSON.parse(this.internData);

     
      //  this.internData.push(12);

      return this.internData;
    },
    whatFormat(){
      console.log(typeof this.internData)
    }
  },
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>


<html>
  <body>
    <div id="app">
      <h5> {{ data }}</h5>
     
       <input v-model="internData" @input="onInputme" />
      
       <button type="button" @click="transformData">click to transform</button>
   <button type="button" @click="whatFormat">what data type</button>
    
   
    
    </div>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    
   
  </body>
</html>

Answer №1

The current issue you're facing is that the internData is not being updated in the transformData function. You should reassign internData with the JSON parsed format inside the function as shown below:

transformData() {
  this.internData = JSON.parse(this.internData);
}

OR

Alternatively, you can turn transformData into a computed property and monitor the type of transformData. This way, you can eliminate the need for the click event to parse the data.

new Vue({
  el: "#app",
  data() {
    return {
      datatype: "foo",
      internData: "[1, 2, 3]",
    };
  },
  methods: {
    whatFormat() {
      console.log(this.transformData);
      console.log(typeof this.transformData);
    }
  },
  computed: {
    transformData: function () {
      return JSON.parse(this.internData)
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <input v-model="internData" />
  <button type="button" @click="whatFormat">what data type</button>
</div>

Answer №2

The function transformData you have created successfully transforms the given string. However, it seems like the transformed object is not being assigned to the internData property as intended.

To fix this issue, you can simply modify your code snippet as follows:

transformData() {
  this.internData = JSON.parse(this.internData);
},

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

Issue with PHP incorrectly encoding JSON when writing to a file

I encountered a problem while working on this task. I used preg_split in PHP to create an array. However, my challenge now is converting it into JSON format. Despite trying several methods, the resulting code appears poorly written and does not seem to be ...

Utilizing the POST route as a middleware: a step-by-step guide

I am working on 2 different routes users.js POST api/users auth.js POST api/auth/confirmation My goal is to utilize the auth/confirmation as middleware in the /users route Initially, I attempted to create a temporary function and use res.redirect(... ...

Providing settings to Vue.js components that have been globally registered

When registering my Vue.js components, I follow this pattern: In the index.js file of a separate reusable npm and webpack project called myComponents: import MyButtons from './src/components/my-buttons.vue' import MyInput from './src/compo ...

Is it possible to host the manifest.Json file on a different domain?

I attempted to include a Manifest.Json file hosted on a different domain in my Blogger site. However, I encountered a warning regarding the Start_URL. Here is the code I used: <link rel='Manifest' href='https://cdn.rawgit.com/ajaymalik14/ ...

ng-display does not display content when the condition switches to true

I am facing an issue with displaying an image and a YouTube video in my HTML. My goal is to show the image when the video is not playing, and switch to displaying the video when it starts playing. Upon loading the page, only the image is shown, which is ...

Error rotating the camera in Three.js

I can't figure out why Firebug keeps throwing an error that says "THREE is not defined" for my var camera. It's confusing because I clearly see the THREE declaration on the right side of the equals sign. init(); animate(); ...

Using Python along with Selenium and PhantomJS to incorporate custom alerts similar to those found in

I attempted to use a Python script to trigger a Javascript alert for reboot confirmation on a DSL modem, but encountered an exception. Here is the code snippet I used: #!/usr/bin/env python import selenium import time from selenium import webdriver cap ...

What is the best way to retrieve child elements from JSON within an Angular JS controller?

I'm having trouble understanding how to ensure the resource call completes before assigning the data.properties to $scope in my controller. My confusion lies here: The resource call returns the following response: [ { "PreAlertInventory": "5.00 ...

Issue with floating navigation bar functionality when resizing the page

After much tinkering, I have managed to create a floating navigation bar for my website. Most of the time, it works perfectly fine, but there's an issue when the window size is adjusted in the floating mode. Take a look at the image below for referenc ...

We regret to inform you that the request cannot be processed by our Express

Currently, I am in the process of learning nodejs and expressjs and attempting to integrate it into the Spring MVC pattern. My intention behind this is to maintain cohesion within my files. However, the results are not quite aligning with my expectations.. ...

Utilize browser caching effectively with Firebase and Angular 5 to optimize website performance

After running my Angular 5 website through Google's PageSpeed Insights, it flagged an issue regarding leveraging browser caching. The specific files mentioned were: https://use.typekit.net/####.css (10 minutes) https://www.googletagmanager.com/gtm.js ...

Dynamically load rows using Ajax calls

I have content that loads dynamically based on search results. (check it out below) (stackoverflow won't let me embed the image as I'm still a newbie) https://i.sstatic.net/n7KoE.png Here's the code snippet for the above; echo &apo ...

JavaScript onclick event triggers only the second audio to play

Does anyone have experience with adding sound effects to a website? I'm attempting to have a positive sound play when the correct image is clicked and a negative sound play when the wrong image is clicked. However, regardless of which image I click on ...

Having difficulty updating the border color of Material UI Input when it is in focused or unfocused state

I can't seem to figure out why this code isn't working as expected. I'm trying to target the MuiInputBase-root element, specify that it should have a blue border by default, and then change the border color to red when focused. Can someone h ...

What is the process for obtaining the source code for children in React?

Can React extract the source code from children props? Imagine having a component with the following structure... <SomeComp> <Heading>I want to access this code inside the Heading tag</Heading> </SomeComp> How can I retrieve t ...

Shifting around haphazardly positioned crates using the cursor

I've successfully developed a program that fills the canvas with randomly positioned boxes of various colors. While this task was relatively easy, I'm now facing a challenge in moving these colored boxes around using my mouse. Additionally, I wan ...

AngularJS single-page application with model-view-controller style designs

Hey there, I'm relatively new to AngularJS and currently on a steep learning curve. I've been working on developing an AngularJS SPA and have grasped the basics. I'm using ngRoute for routing and have put together a basic application framew ...

Trigger the input with a delay function, pause if the input value is modified

I am in the process of creating an angular directive that will run a function when the input value changes. I want to implement a 300ms delay before running this function, but if the value changes again within the 300ms timeframe, I need to reset the delay ...

The jQuery click event not triggering on ASP.NET control

I am currently developing a C#/Asp application that utilizes jQuery. I am trying to implement a specific function that should be called every time a click event is triggered on an element with a class of "loadingInProgress". However, the code snippet belo ...

Why is it not possible to declare an interface or type within a TypeScript class?

I am struggling to define interface | type within a TypeScript class. Here is the code snippet: class MyClass { interface IClass { name: string, id: string } } However, I keep encountering this error: Unexpected token. A constructo ...