Vue Js Convert Array into Object:
Vue.js is a JavaScript framework that simplifies building user interfaces. Object.assign() is a method that copies the values of all enumerable properties from one or more source objects to a target object.
To convert an array into an object using Object.assign() in Vue.js,The result will be an object where each element of the original array is a property with a unique key.
In summary, by using Object.assign() in Vue.js, you can easily convert an array into an object with each element of the array being a property of the resulting object.
How can I convert an array into a object using Vue.js?
This code creates a Vue application and binds it to an HTML element with the ID “app”. The Vue application has a data object with two properties: “array”, which is an array of strings, and “obj”, which is an empty object.
The mounted hook is used to assign a new object to the “obj” property, which is created by using the Object.assign() method to copy the values from the “array” property.
Vue Js Array into Object Example
<div id='app'>
<p>Array: {{array}}</p>
<p>Object: {{obj}}</p>
</div>
<script type="module">
const app = new Vue({
el: "#app",
data() {
return {
array: ['101', 'John', '25', 'developer'],
obj: {},
};
},
mounted() {
this.obj = Object.assign({}, this.array)
},
});
</script>
Output of Vue Js Convert Array into Object
Using Spread Operator to Copy Arrays and Assign to Objects
It uses the spread operator to create a copy of the array and assign it to the object. However, since the spread operator creates a new array with numeric indices, the resulting object will have those indices as its properties, rather than the original array’s values.
Vue Js Convert Array into Object using Spread Operator | Method 2
<script type="module">
const app = new Vue({
el: "#app",
data() {
return {
array: ['105', 'Andrew', '34', 'Marketing'],
obj: {},
};
},
mounted() {
this.obj = {...this.array}
},
});
</script>