How to convert a string into an object in VueJS?

Hi Friends đź‘‹,

Welcome To SortoutCode! ❤️

To convert a string into an object in VueJS. There are several methods to convert a string into an object, we are going to use JSON.stringify(Obj) methods. In these methods Obj stand for your object data.

Short solution

parentComp.vue

var Obj = "{id:1,sitename:'sortoutcode'}"; //object

ObjA = JSON.stringify(Obj);

console.log(ObjA); //string

Today, I am going to show you How you convert the object to a string in VueJS?

Table of Content

  • Setup the Vue (Optional)
  • Create FirstComponent.vue and import it into App.js
  • Convert an object to a string using JSON.stringify()

This article will guide you to How do I convert a string into an object in vueJS

Setup the Vue.js

First, we have to install the Vue project, I had installed the vueJS in my system. If you haven’t installed or have any problem with installation you can follow this article, it will show you step by step process of installation.

How to Install the VueJS project?

Create FirstComponent.vue and import it into App.js

Create the new component in the src/components/ components folder. The component name is FirstComponent.vue and imported into the App.js file:

App.js

<template>
  <FirstComp />
</template>

<script>
import FirstComp from "./components/FirstComp.vue";
export default {
  name: "App",
  components: {
    FirstComp: FirstComp,
  },
};
</script>

Convert an object to a string using JSON.stringify()

To convert a string into an object in vuejs. We are going to define the object Obj in the data property. And we are going to convert this object into a string using the JSON.stringify(Obj).

Let’s take a short example to better understand.

FirstComp.vue

<template>
  <div class="app-data">
    <h1>Welcome to sortoutcode.com</h1>
    <div>
      <p>Obj: {{ Obj }}</p>
      <p v-if="output">Output: {{ output }}</p>
      <p v-if="output">Type: {{ typeof output }}</p>
      <button @click="showData">Convert</button>
    </div>
  </div>
</template>
<script>
export default {
  name: "FirstComp",
  data() {
    return {
      Obj: '{"name":"sortout", "age":1, "URL":"https://sortoutcode.com/"}',
      output: "",
    };
  },
  methods: {
    showData() {
      this.output = JSON.parse(this.Obj);
    },
  },
};
</script>

For now, let’s check the output.

Output

con string into object object

Links

Here, is the above program code sandbox link of how to convert a string into an object in vue js. Then you can use it whenever you went and do the changes as per your requirements.

Codesandbox

All the best đź‘Ť.

Follow me on Twitter