Vue Js Convert Object into Array:Vue.js is a popular JavaScript framework that allows developers to build interactive user interfaces. One common task in Vue.js is to convert an object into an array using the Object.keys() method. This method returns an array of a given object’s own property names.
To convert an object into an array using Object.keys() in Vue.js, you can first create an empty array and then loop through the keys of the object using a for loop. In each iteration, you can push the value of the current key in the object to the array. This will create an array with all the values of the object’s properties.
How can I convert an object into an array in Vue.js?
This is a Vue.js script that creates an app with two pieces of data: an object called “myObj” and an empty array called “items”. The “mounted” function runs when the app is loaded and populates the “items” array by iterating through the keys of the “myObj” object and creating an array of objects with each key-value pair as a “key” and “value” property. This array is then assigned to the “items” variable. The HTML code displays the “myObj” object and “items” array using Vue.js template syntax.
Vue Js Convert Object into Array Example
<div id="app">
<p>Object :{{myObj}}</p>
<p>Array: {{items}}</p>
</div>
<script type="module">
const app = new Vue({
el: "#app",
data() {
return {
myObj: {
name: "John",
age: 30,
occupation: "Developer"
},
items: []
}
},
mounted() {
this.items = Object.keys(this.myObj).map(key => ({
key,
value: this.myObj[key]
}));
}
});
</script>