AngularJS disrupts the JSON data format

Upon receiving data from the server in JSON format, I have noticed that it is not displaying in the expected order:

[{
  "outlet_id": 83,
  "outlet_name": "My Outlet",
  "address": "My Outlet",
  "shop_number": "123",
  "street": "123",
  "building_no": "52",
  "key_location": "Location 123",
  "mohallah": "Mohalla 123",
  "landline": "1235869",
  "owner_name": "Owner",
  "Manufecture": "A",
  "BrandName": "B",
  "Variant": "C",
  "BRANDDiscription": "D",
  "SIZE": "E",
  "Variant/Promotions": null,
  "Segment": null
}]

When using ng-repeat to display this data, the attributes do not appear in the same order as in the original JSON. Here is an example of how I am attempting to display the data:

<td ng-repeat="(key, value) in vm.outletFieldAttrsList[0]">{{value}}</td>

If anyone has any insights or solutions on how to maintain the correct order of attributes when displaying JSON data, I would greatly appreciate your help.

Answer №1

The arrangement of attributes in JavaScript objects is not assured. To maintain order, it's recommended to use either an Array or a Map.

Related:

Exploring AngularJS sorting by property

Answer №2

In Javascript, "objects" do not follow a specific order - for example:

{ "e": 0, "b": 123, "c": 345"...

The enumeration of this object will not be in the order it was defined as e, b, c; instead, it will be shown as b, c, e (alphabetical order).

To properly enumerate objects in JavaScript, you need to store the order in a separate entity, such as an array ["e", "b", "c"].

Answer №3

It appears that attempting to use arr.sort may not always produce the desired outcome.

When using the sort() method to arrange elements in an array, the sorting process takes place within the array itself and returns the modified array. However, it is important to note that the order of sorting is not always stable. By default, the elements are arranged based on Unicode code points of their string representations.

If a compareFunction is not specified, the elements will be sorted by converting them into strings and comparing these strings based on Unicode code point order. For instance, "Cherry" will come before "banana". In a numeric sort, 9 will come before 80 numerically, but due to string conversion, "80" comes before "9" in Unicode order.

To ensure that the response is ordered as desired, a solution would involve customizing the comparison method.

For example:

[0: { ITEM }, 1 : {ITEM 2}]

Alternatively, you can create a comparison function like this:

items.sort(function (a, b) {
  return a.localeCompare(b);
});

For further information, visit this resource.

Answer №4

I have managed to find a solution for this issue:

<td ng-repeat="key in objectKeys(outletFieldAttrsList[0])"> </td>

On the controller side, I implemented the following:

$scope.objectKeys = function (obj) {
           
        return Object.keys(obj);
    }

The Object.keys method will return the keys of the object in the same order they exist.

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

A step-by-step guide on implementing lazy loading for a specific div section using either AJAX or Java

I'm facing an issue with a div section that contains numerous tables pulled from my database. The main problem here is that when the page loads, it takes a considerable amount of time to fully load all the content, causing a significant delay. Could ...

Exploring arbitrary JSON keys with dynamically computed properties in Ember

In a specific scenario, a Model includes a JSON attribute for various configurations: configuration: DS.attr(). There is a configurationService (initialized in every component/route/controller/…) with computed properties designed to easily access these ...

Using jQuery and regex to validate a long string containing lowercase letters, uppercase letters, numbers, special characters, and

Good day, I've been struggling with jquery regex and could really use some assistance. I've been stuck on this since last night and finally decided to seek help :) Here is my regex code along with the string stored in the 'exg' variabl ...

Managing a collection of user inputs in React

I am working on a table where I have to create a list of input elements. These input elements will come with a default value which can be changed by the user from the maximum number (default value) down to 0, or they can send this maxNumber. There is also ...

Tips on how to update a NG-Table that has been populated with data from an http request and has

Looking to update the data in my ng-table dynamically. The following screenshots illustrate the entire process: Upon clicking "search" for BrandID, a new modal window appears: Within this modal, there is an ng-table displaying some pre-loaded data. Upon ...

Sails.js navigating through sessions

What is a rolling session in Sails.js? A rolling session is a session that expires after a set amount of time without user activity, except for websockets live updating data. If the user navigates to a different part of the site before the session expires, ...

When using Lockdown.js with NPM, I encounter a blank file being returned

When using Lockdown.js for NPM, I encountered an issue where the command to generate the lockdown file resulted in an empty file. Here are the links for the dependencies: NPM lockdown git Here is a snippet from my package.json: { "name": "nw", "pri ...

Access to this page via the Odesk API in node.js is restricted and unauthorized

/** * Here is an example of how to use the oDeskAPI * * @package oDeskAPI * @since 09/22/2014 * @copyright Copyright 2014(c) oDesk.com * @author Maksym Novozhylov <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data ...

Opinions on crafting a new gadget?

I will only provide each website interested in my widget with the code to copy and paste once. It is crucial that the code is future-proof. After much consideration, this is the widget code I have developed: <script type="text/javascript" src="http:/ ...

I'm looking to showcase information from a nested JSON file within the ng-click event in Angular. How can this be achieved effectively?

I am currently exploring ways to display nested JSON data that relates to the data retrieved from the previous ng-click event. Any suggestions or insights on this matter would be highly appreciated. Thank you! Check out the plunker example here: http://p ...

Unable to establish a connection with the node at http://localhost:8545

Issues Encountered: I am having trouble with the Web3.min.js path in my system directory! The Web3.min.js file is being loaded from a folder in my browser. I have copied the web3.min.js file to the same folder where the index.html file is l ...

Should I keep my Mobx stores in a dedicated file or include them directly in the React component?

There are a couple of ways to define observable properties and actions in MobX. One way is to include them directly in the component like this: // App.js class App extends Component { @observable a = 'something' @action change() { this. ...

Error SCRIPT438: Property or method not supported by object in Internet Explorer

Within my application, there is an option for users to deactivate their profiles, which can only be reactivated by the admin. I have created a class called ActivateProfile with two methods: userExist(userName) to check if a user with the given userName ...

The animation only applies to the initial item in ngRepeat

After implementing async data loading in my application, I noticed that NgRepeat only animates the first element in an array. Check out the example on jsFiddle Here is the HTML code snippet: <div ng-repeat="x in data"></div> And here is the ...

Parsing JSON data using Alamofire in Swift

I have received some JSON data through an Alamofire GET request structured as shown below. { "result" : { "id" : 3456543 }, "error" : 0, "success" : "True" } Is there a simple way to parse through this data and store it in a class, similar to ...

Incorrect scoring method in Fuse.js

I recently integrated Fuse.js into my discord bot to create a search function. Interestingly, when I input the search query "Paper Beauty (Awakened)", it retrieves a similar item as the top result in the array. Search Results: [ { item: 'Paper ...

Switch between class and slider photos

I am currently having an issue toggling the class. Here is the code I am working with: http://jsfiddle.net/h1x52v5b/2/ The problem arises when trying to remove a class from the first child of Ul. I initially set it up like this: var len=titles.length, ...

How can I create a Material ui Card with a border-less design?

After reviewing the information provided, I noticed that you can set the option to have it as variant="outlined" or raised However, I am curious if there is a method to create the card without any visible borders at all? ...

Assurance-driven number tally

I'm diving into JavaScript and recently started exploring promises. I've put together a code snippet that logs the value passed to the promise function as a parameter after the setTimeout function is triggered. Now, I'm wondering if there&ap ...

Swap out AJAX following a successful retrieval and when managing errors

I currently have a basic AJAX load function set up to load a specific URL: <div id="load"> <h1 id="status">Loading...</h1> </div> <script type="text/javascript"> $(document).ready(function(){ $.ajaxSetup({cache: false}); var ...