Creating a structure for a JSON array in ExtJS - step by step guide

The information retrieved from my server is in the following format:

["admin", "user", "developer", "super"]

I am working on transforming this data into a new model structure represented by:

Ext.define('RoleModel', {
      extend: 'Ext.data.Model',
      //fields: [{}]
});

This is how my store is structured:

 Ext.create('Ext.data.Store', {
      model: 'RoleModel',
      proxy: {
          type: 'ajax',
          url : '/roles',
          reader: {
              type: 'json'
          }
      },
      autoLoad: true
  });

Is there a way to correctly assign the single array received from the server to my RoleModel?

Answer №1

Before you can parse your JSON into your data model, it must be formatted as shown below:

[
    { "role": "admin"     },
    { "role": "user"      },
    { "role": "developer" },
    { "role": "super"     }
]

However, if you are using ExtJS 5.x, there is a more efficient way to handle the Ajax call by applying a transform on the proxy's reader. Here is an example:

Ext.create('Ext.data.Store', {
    model: 'RoleModel',
    proxy: {
        type: 'ajax',
        url : '/roles',
        reader: {
            type: 'json',
            transform: function(data) {
                return data.map(function(x){
                    return { role: x };
                });
            }
        }
    }
});

» Fiddle

Answer №2

To solve my issue, I decided to include a role attribute in my model and implemented the following code snippet:

Ext.Ajax.request({
  url: '/roles',
  success: function(response){
    var jsonData = Ext.JSON.decode(response.responseText);
    var rolesArray = jsonData.map(function(r){ return {role: r}});
    store.loadData(rolesArray);
  }
});

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

Add the current date plus 48 hours to the content on a webpage (JavaScript maybe?)

Hello there, I am currently in the process of setting up a small online store for a farm using Squarespace. One thing I would like to implement is specifying that items will be available for pickup two days after they are purchased online, instead of imme ...

A high volume of users connecting to the application causes Node.js and path.js to crash

Hey everyone, I've got an Express.js application up and running with socket.io for real-time data display to users. However, once the number of users on the website exceeds 10, my Node servers crash with the following error message: path.js:309 var ...

Steps for Removing Multiple CSS Styles from an Element's Style:

When my application generates inline styles, I sometimes need to remove the height, width, and max-width styles from certain elements. I have identified the element using this code: const elems = window.$('.myElements'); window.$.each(elems ...

What is the best way to declare a variable within a VueJS v-if condition without it being visible?

In my code, I have a specific template that is displayed when a certain condition is met using a v-if statement. In this template, I need to set a variable to N/A, but I am struggling with how to accomplish this simple task. <span v-if="se ...

Is it possible to activate the jQuery .click() function for a button with specific text?

Here's a dilemma I'm facing: $('.add_to_cart span:contains("Choose a Size")').click(function() { console.log("it has been clicked") }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></s ...

Converting Database Array to JSON in PHP

Currently, I am in the process of querying a MySQL database to retrieve results based on an input value. Once the data is fetched, it is added to an array and then encoded into JSON. The code is functioning as expected at the moment but there is an issue ...

Linking a JSON or JSON array to a Grails object

When I receive a response in the form of a JSON array, it can either be an array of values like ['1', '1', '2'] or an array of objects like [{'name': 'blabla', age: '30'}, {'name': ...

Detecting When a User Reaches the Bottom of the Screen in REACTjs

My goal is to monitor when the user reaches the bottom of the screen and then trigger a function to load more data. Within my app.js file, I have a Products component that handles the data fetching. The Products component is enclosed in a div with a class ...

Obtain similar words and related terms

My goal is to extract information from www.thesaurus.com, specifically related to synonyms and antonyms of a word. In this case, let's consider the word angry. I am interested in the words displayed in these images (focusing only on the first 2 blocks ...

I am encountering difficulty with importing this particular file

I am struggling to get this image to display on my webpage using React. Despite reading through the Facebook documentation, I am still unable to figure it out and feeling quite frustrated. Any help would be greatly appreciated. https://jsfiddle.net/gexcoz1 ...

trouble with synchronizing multiple requests in node express mysql

An expressJS endpoint is connected to a mysql DB, where a query retrieves a set of data and assigns the first returned result to a user by updating a field with the user id. The rule is that a single row can only be allocated to one user until the user pr ...

I'm looking to instantiate a Backbone collection outside of a script - how can I do that?

I have created my backbone collection named "Events" with a model called "Event". I want to create the backbone collection in this manner: Check out my code below: <script src="<?php echo site_url(); ?>js/backbone-calendar.js"></script&g ...

Step by step guide on rotating a plane with texture by 90 degrees

I've been working on developing an fps game, but I'm encountering an issue where the floor disappears from the scene when I try to rotate it close to 90 degrees. Here's the code snippet responsible for creating the plane. var colorMap = new ...

Trigger a PHP function with an image's OnClick event

In my PHP class, there is a method called delete. I am trying to call this method when clicking on an image, but the following line of code does not work: echo "<img src='icon/del.gif' onClick='.delete()'/>" I also attempted us ...

Choosing an option beforehand using angular-ui-select2 version 0.0.5

I'm struggling with setting a default option in a select2 dropdown using Angular and an ng-model. Here's my implementation: Angular controller code snippet $scope.filter = { searchValue: '', departmentId: 'Department2' } ...

Is there a more efficient method to achieve the desired effect without making multiple calls to jQuery ajaxSuccess?

Currently, I am working on creating an effect that involves a quick fade-out followed by a fade-in of the element once the request is successful. Since jQuery processes elements in a routine manner (top to bottom), I have managed to achieve my desired eff ...

Creating a duplicate of a square in JavaScript

For a web development assignment, I am tasked with cloning a square 7 times and increasing its number by 1 each time (from 1 to 8). I'm considering using a "while" loop with an incrementation until i = 8, but I'm unsure. Also, I'm wondering ...

How can I dynamically populate a multiple select box with data from a PHP query and store it in a multidimensional array using jQuery?

I apologize for any language barriers as English is not my first language. My query is as follows, I am looking to implement three multiple select boxes on a single page. How can I retrieve query data before it is executed in PHP? Each loop result will be ...

Position the <a> to the right side of the div

Is there a way to right-align the <a> element, which contains a Button with the text Push Me, within the <div> (<Paper>)? https://codesandbox.io/s/eager-noyce-j356qe This scenario is found in the demo.tsx file. Keep in mind that using ...

The animation did not cause a transition to occur

After creating a search modal triggered by jQuery to add the class -open to the main parent div #search-box, I encountered an issue where the #search-box would fade in but the input did not transform as expected. I am currently investigating why this is ha ...