Working with Vue 3 Composition API: manipulating an array of objects

I am working with an array stored in an external JSON file named "West.json"

{
    "west" : [
        {
            "id" : 1, 
            "state": "CA"
        },
        {
            "id" : 2, 
            "state": "AZ"
        },
        {
            "id" : 1, 
            "state": "WA"
        }
    ]
}

In a Vue file, I have imported the json file. Now, I am trying to create a new array containing only the values of "state". How can I achieve this?

Currently, I access a value like this:

import { west } from "../json/West.json"

const state = computed(() => {
     return west[0].state

I would like to iterate over the array and get something like this:

{"state": [{"CA"}, {"AZ"}, {"WA"}]}

Your help is greatly appreciated.

Answer №1

In order to have an object containing the states, such as {"CA"}, you need to include a key. You can achieve this by using an array like

[{state: "CA"}, {state: "AZ"}]
. Here is an example of how you can do it:

return { state: west.map(item => ({state: item.state}))}

Another way to handle this is by accepting the data in the format ["CA", "AZ"]. In this case, you can use the following code:

return { state: west.map(item => item.state)}

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

Information displays instantly in the initial milliseconds

When developing dynamic web pages with Nuxt, I encountered an issue in the pages directory where a file named _url.vue is located. The contents of this file are as follows: <template lang="pug"> div component( v-for= ...

Verify if the item already exists in the Vue.js array

Here is the data I have: data: function() { return { conversations: [ ] } } I am retrieving my data from the response object using response.data.conversation Is there a method to verify if this.conve ...

Utilize data attributes in VueJS to dynamically style elements

Is there a way to utilize the data() values within the <style>..</style> section? I have experimented with different combinations (using/omitting this, with/without {{brackets}}, etc.) but haven't been successful. Interestingly, when I man ...

Set the value of an input without using v-model or any form of data binding

In the v-for loop, I want to populate some input fields with predetermined text without attaching them to the object. My current attempt looks like: <div v-for="item in allItems"> <input type="text" class="header-title" value="item.name">< ...

Using the mapState function in vuex allows for easy access to Vue methods

I have an important task to complete while the data is being computed using vuex mapState. I must ensure that the vue method countAlerts is called every time the data changes; however, the computed property needs to invoke this method and unfortunately, ...

Encountered error code 422 Unprocessable_entity upon submitting form to Rails API via Vue.js application

Currently, I am in the process of developing an application using Rails 6 Api as a backend and Vue as a standalone web app. After successfully setting up my sign-up form, I encountered a frustrating issue upon submission where I received a Completed 422 U ...

Is it possible that the v-if directive is not functioning properly with the script setup in vue2.7? Have the syntax requirements changed in vue2

<template> <div> <button @click="handleClick">toggle</button> <span v-if="isToggled()"> hidden message </span> </div> </template> <script setup lang="ts" ...

"Enhance your Vue components with a directive to customize or adjust element attributes

I have a variety of elements structured like this: <some-custom-component :errors="formErrors.has(getErrorKey('town'))" :error-messages="formErrors.getAll(getErrorKey('town'))" ></some-custom-component> The formErrors ...

Troubleshooting image display issues in Vue components when using Vite with Laravel

Previously, all of the images were displaying correctly until I started using Laravel with Vite. Now, the images from inside Vue components have stopped working and I can't seem to find a solution for this issue. The images are stored in Laravel with ...

Tracking and managing user clicks on external links within a vue.js application

I am currently working on a web application that retrieves data from a CMS. Utilizing the Vue-Router in 'history' mode, I need to address content fetched from the API which may include links. My goal is to manage specific links using the router w ...

Understanding the separation and communication techniques in Vue.js components

I recently developed a small vuejs application and I find myself getting confused with the functioning of components. Here is the code snippet that I have been working on: <div id="app"> <div v-if="loggedIn"> <nav> <r ...

Unlocking the power of namespaced Vuex getters in Mocha unit testing

I have been working on developing a new Vue component that utilizes a namespaced Vuex getter to retrieve a list of column names. The actual component is functioning properly and runs without any issues. During the Mocha unit testing phase, I set up a mock ...

Bidirectional Data Binding with Computed Setter in Vue.js

Exploring the concept of two-way data binding with a basic example: <template> <input v-model="fullname"/> <input v-model="first"/> <input v-model="last"/> </template> <script> var app = new Vue({ el: '#a ...

Utilizing Django in conjunction with Vue to identify and address form validation errors

Utilizing a Django ModelForm with crispy forms for display on the template, upon completion of filling out the fields and clicking Submit, an email is triggered in the backend using Django's send_email functionality. However, the issue arises from th ...

How can I modify the Layout of my Quasar App to move the left Drawer to the right side?

I find myself struggling with the arrangement of Quasar and it's not quite clicking for me, even after going through the documentation. The scaffolder presented me with this code snippet. However, it positions the Drawer on the left side. Is there a ...

Error: serialport in node_modules throwing unexpected token SyntaxError

I have been attempting to run the vue-electron app, but I keep encountering this error. App threw an error during load C:\newFolder02\pos4-desktop\node_modules\@serialport\stream\lib\index.js:103 const settings = ...

Using the Postman application, the Sequelize delete request with payload functions correctly; however, it encounters issues when executed through the Vue

Struggling to send PUT and DELETE requests via my express backend to a sqlite database. PUT request is working, but DELETE request consistently fails. Verified headers in the network tab, both are correct (application/json). Postman can successfully delet ...

Step-by-step guide for setting up vuetify within Laravel 9 starter kits

Currently, I am in the process of setting up Vuetify within my Laravel 9 project that utilizes the Breeze Vue starter kit. Can anyone provide guidance on how to properly install Vuetify? Should I directly install it into the project, or is there a specifi ...

Having trouble with a method that isn't providing values during interpolation in Nuxt.js/Vue

Within the static folder of my nuxtjs application, there exists a file named data.json Utilizing this data within my component is done as follows: <script> import data from '~/static/data.json'; export default { data ({ params }) { ...

Unusual Methods in Vue.js: Exploring Odd Behavior

In my application, I have a single data variable called message, as well as a method in the methods section that performs cryptographic algorithms. Below is the code snippet: export default { data: () => ({ message: "" }), methods: { clic ...