2

I'm initializing an object in angular with un-ordered key defined but when I print it on html it automatically changes to alphabetically.

I've tried to resolve using tslint.json to set some rules like as follows

{
    "extends": ["tslint:recommended"],
    "rules": {
        "object-literal-sort-keys": false 
    }
}

as well as

"jsRules":{
    "object-literal-sort-keys": false,
}

but nothing effect on expected output.

initialize object in App.component.ts

abc: Object = {'State': 'asd', '1': 'roshan', '2': 'ramanuj', 'city': 252};

app.component.html

<div>{{ abc | json }}</div>

I expect the output is {"State": "asd", "1": "roshan", "2": "ramanuj", "city": 252 } but actual output is { "1": "roshan", "2": "ramanuj", "State": "asd", "city": 252 }

  • Note that tslint has nothing to do with the runtime behavior, it's just a set of rules that your editor (like vscode) uses to give you errors/warnings when coding. – ShamPooSham May 24 '19 at 06:50
  • yes i know this but i try it because i assume to may be it can effect on compile time changes and get output but it not effect. But this ordering where perform i can't detect – Pradip Talaviya May 24 '19 at 07:17
  • Ok, but tslint has no effect on the compiler either. It's simply to give the coder feedback while coding. – ShamPooSham May 24 '19 at 08:39
  • i understand it destination of Coding standards for pacific language like ES, TS, JS and etc, Editors can use for document formatting – Pradip Talaviya May 24 '19 at 08:57

1 Answers1

0

You should define an array here

abc = [ {name: 'Ramesh'}, { name: 'asd'} , {name: 'avinash'}, {name: 252} ];

Use ngFor to print it

<div *ngFor="let item of abc">{{item.name}}</div>

Umesh
  • 2,704
  • 19
  • 21
  • 3
    i think your not understand my problem, issue is not name issue **why key was auto sorting in printing not same as initialize** – Pradip Talaviya May 24 '19 at 06:27
  • In JS object, the key are enumerated when traversed and it is automatically ordered by JS. In your case, the keys are both numbers and strings. You need a better data-structure if you need to overcome your issue. You should use array here. For reference, you can take a look at [this](https://www.geeksforgeeks.org/object-keys-javascript/) – Umesh May 24 '19 at 06:38