What is the best way to link my JSON object to specific properties of my data object in vue.js?

I am currently using Vue.js for my frontend development and I have a JSON object that I need to map to set certain properties in my data().

I have confirmed that the server connection is working and that the JSON object is received properly.

In my computed() method, I have implemented logic to map all items from the JSON object, set the property values, sort them alphabetically, and then display them in the view.

I have searched on StackOverflow but couldn't find a solution to my specific issue.

I came across some information in the Vue documentation about Vue.set, but I am not sure how to apply it in my case: https://v2.vuejs.org/v2/api/#Vue-set

data: function() {
    return {
      itemListModel: {
        className: "myStuff",
        items: [],
        name: "",
        id: "",
        description: "" 
      }
    }
  },
  
  methods: {
    mapToModel: model => {
      return model.items.map(element => {
        return {
          className: model.className,
          value: element.items,
          id: element.id,
          name: element.name,
          description: element.description
        };
      });
    },
    getAllItemsFromDb() {
      const url = "https://localhost:44339/ListAll";
      axios
        .get(url, {
          headers: {
            "Content-Type": "application/json"
          }
        })
        .then(response => {
          this.itemListModel = response.data;
        });
    },
    
    computed: {
      categorizedItems() {
        let allItems = this.mapToModel(this.itemListModel);
        alert(allItems);

        //code continues for other logic
      },
      itemResultsFromDB: function() {
        let vm = this;
        return vm.wordListModel;
        //this gets the JSON Object from the database and sets the itemListModel if it is an empty object. The class name, items, name, id and description are in the JSON object from the backend that I'd like to access.

      }

The JSON object structure is as follows:

{"myStuff":[{"name": "foo", "id": "guid-string", "description": "blah,blah..."}]}

"Error, cannot read property of 'map' of undefined at VueComponent.mapToModel"

How can I resolve this issue?

Even when I edit my itemListModel to just an empty object {}, I still encounter the same error.

Answer №1

It appears that there may be a issue with mapping the database data as the structure seems to be different than expected.

Here is the data:

{"myStuff":[{"name": "foo", "id": "guid-string", "description": "blah,blah..."}]}

And here is your object:

   return {
      itemListModel: {
        className: "myStuff",
        items: [],
        name: "",
        id: "",
        description: ""
      }
    }

Make sure to map the data correctly when retrieving it from the database.

      const key = Object.keys(response.data) // The key here should be `myStuff`
      this.itemListModel = {
        items: response.data[key],
        className: key
      }

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

SyntaxError: End of input caught unexpectedly (NodeJS TCP server)

My simple tcp server has the capability to send and receive json data. Here is a snippet of my code: // Handling incoming messages from clients. socket.on('data', function (data) { var obj = JSON.parse(data); if(obj.type == "regis ...

Fluid Chart Arithmetic Calculations

Greetings esteemed individuals of StackOverflow, I am currently working with an exchange rates file in XML format that I am converting to JSON within an Azure logic app using Transform XML To JSON. The XML contains two rates (Ask and Bid) and a node in the ...

Sort an array using another array as the reference in JavaScript

I have encountered similar questions before, but my current challenge involves partially sorting an array based on values from another array. This is what I aim to achieve: let array = [ { name: "Foo", values: [a, b, c, d] }, { name: " ...

Implementing a feature in ReactJS that enables users to select a minimum and maximum limit for checkboxes

I have developed a unique React application that incorporates JSON values into checkbox elements. The JSON data includes both minimum and maximum required values. I successfully implemented a function to set the checkboxes' maximum value based on the ...

Having trouble simulating a service using nuxt and jest

In my project, I have created a component named External.vue. This component includes a button with props and triggers a Google Analytics event whenever it is clicked. <template> <div> <button ref="ctaButtonExternalElement&q ...

What is the method for extracting information from a JSON file?

Hello there, I am facing an issue with retrieving data from a JSON file. Previously, the format of the JSON data looked like this: {"country":"US","Money":"Dollars US"} In order to extract the result, I used the following code in my inner class called A ...

What is the best way to make an element disappear 5 seconds after the mouse has stopped hovering

#section1 { display: block; } #section2 { display: none; } #container:hover > #section2 { display: block; } <div id="container"> <div id="section1">Section1</div> <div id="section2">Section2</div> </div> ...

Error: Python expected a string or bytes-like objectTypeError

Currently, I am attempting to tally the number of components based on the data from a json file. Outlined below is my current approach: # Function to count the components def get_component_count(data, component_name, locator_name, counter=0): if re.m ...

I'm encountering an issue with enabling Node.js support on PhpStorm as it keeps freezing at the dialog box. Does anyone have a solution for this problem?

Seeking assistance with configuring code support for Vue files in PhpStorm v10.0. Despite having Node and Vue plugins installed, my laptop also has Node(v10.16.3) downloaded. Encountering an issue where PhpStorm freezes at a dialog box, as shown in the sc ...

React callbacks involve the interaction between three different components

Currently, I am working with 3 distinct components: -The friendsPage component contains a list of friends and invitations to friends -The friendComponent displays detailed information about a friend along with possible actions (which are handled in the t ...

Error encountered when attempting to reinitialize DataTable while iterating through multiple tables and searching within tabs

Currently, I am utilizing DataTable to display 3 separate tables with the help of tabs, along with a search function. However, every time I load the page, I encounter a reinitialization error. Here is the snippet of my code: _datatables.forEa ...

Tips for parsing a JSON file within my node.js application?

I am working on a node.js service that involves validating JSON data against a schema defined in jsonSchema. Below is the code snippet for my service: app.post('/*', function (req, res) { var isvalid = require('isvalid'); ...

Troubleshooting: jQuery addClass() function not functioning properly in conjunction with attr("href", something)

I am trying to implement a unique feature for a link using a Bootstrap button, where it only works on the second click. On the first click, the appearance of the link should change slightly. To achieve this, I am utilizing the .addClass(newClass), .removeC ...

I am unfamiliar with this specific JavaScript algorithm problem from Codewars

I need help with a JavaScript algorithm question This problem involves extracting two letters from the middle of odd-numbered characters My confusion lies in function getMiddle(s) { //Code goes here! let answer = ""; if (s.length % 2 !== 0) { a ...

What is the best way to incorporate an icon as a label in a Vuetify select dropdown menu?

I'm exploring Vue/Vuetify for the first time and I am currently working on implementing a select option feature on a website. Instead of using text labels, I would like to use icons as labels, similar to the image provided below. I am unsure if this i ...

Emphasizes the P tag by incorporating forward and backward navigation options

My goal is to enable users to navigate up and down a list by pressing the up and down arrow keys. For example, if "roma" is currently highlighted, I want it to change to "milan" when the user presses the down arrow key. Here is the HTML code I am working w ...

Is there a way to incorporate logic into my Angular routes?

I am looking to secure certain routes within 'case' sections based on the dependency of $scope variables (whether forms are valid or not). var loginForm = angular.module('loginForm',[ 'ngRoute', 'stepsControllers&apo ...

How can Angular 2 and Firebase be used to search for an email match within all Firebase authentication accounts?

Is there a method to verify the existence of an email within Firebase auth for all registered accounts when users sign up? Can AngularFireAuth be utilized in an Angular 2 service for this purpose? My authentication system is established, but now I am work ...

Parsing JSON objects with identifiers into TypeScript is a common task in web development

I possess a vast JSON object structured like so: { "item1": { "key1": "val1", "key2": "val2", "key3": [ "val4", "val5", ] }, { "item2": { "key1": "val1", "ke ...

Module TypeScript could not be located

Currently, I am in the process of converting my nodejs project from JavaScript to TypeScript. I have updated the file extensions from .js to .ts, but now I am encountering errors with require(). In an attempt to fix this issue, I have added the following c ...