0

I have the object properties which contains objects that are all from the same city. In my template I want to display the city name so the order of the items in the object does not matter. How can I select the first property's city name from my AngularJS template?

<p>These properties are in {{$ctrl.properties.???.city}}</span>
properties: {
    '123 Main': {
        city: 'Portland',
        sqft: 2132
    },
    '398 Boardwalk': {
        city: 'Portland',
        sqft: 428
    },
    '20 Broadway': {
        city: 'Portland',
        sqft: 492
    }
}
georgeawg
  • 48,608
  • 13
  • 72
  • 95
Jon
  • 8,205
  • 25
  • 87
  • 146

2 Answers2

4

Order of items in objects is not guaranteed, i.e. it might be different each time. But if you just want any first object, you can get it by the first key:

const firstKey = Object.keys(properties)[0];
return properties[firstKey];
Clarity
  • 10,730
  • 2
  • 25
  • 35
  • Is there a way for me to do this in the angularjs template. Order of items in object doesn't matter. – Jon Aug 26 '19 at 20:30
  • try `{{$ctrl.properties[Object.keys($ctrl.properties)[0]).city}}` – Clarity Aug 26 '19 at 20:32
  • I think you made a typo and meant to use another closing bracket `]` after the 0. I have tried your solution `{{$ctrl.properties[Object.keys($ctrl.properties)[0]].city}}` but I do not see the city name. Can AngularJS template compute `Object.keys()`? There are no console errors. – Jon Aug 26 '19 at 20:42
  • I don't see any data being displayed when I try `{{Obect.keys($ctrl.properties)}}`. This makes me think that AngularJS template is not computing `Obect.keys($ctrl.properties)`. – Jon Aug 26 '19 at 20:45
  • Sorry about the typo. And you're right, seems like you'll need to pass `Object.keys` or result of it to your template manually: https://stackoverflow.com/a/42813708. I think the easiest would be to write a filter called `first` and use it in your template. – Clarity Aug 26 '19 at 20:48
  • 1
    No problem. I was hoping to keep my code clean and simple. I can mark your response as the accepted answer if you update response saying that `Object.keys` needs to be passed into the template :) – Jon Aug 26 '19 at 20:49
1

Use the ng-repeat directive with the (key, value) form and pipe it to the limitTo filter:

<div ng-repeat="(key, obj) in $ctrl.properties | limitTo : 1">
    These properties are in {{key}}
    <ul>
        <li ng-repeat="(prop, value) in obj">
           {{prop}}:  {{value}}
        </li>
    </ul>
</div>

For more information, see

georgeawg
  • 48,608
  • 13
  • 72
  • 95