[Vuejs]-Displaying the first object in vue js

0👍

In a totally static way, you could do this.

<li>{{firstElement}}</li>
data() {
   return {
      CareerLevel: { /* Your data here */  }
   }
},

computed: {
    firstElement() {
      return Object.values(this.CareerLevel.CLLevel)[0].Role[0]
    }
}

To do it “correctly” Id do a recursive method.

0👍

I would suggest you to use computed property for this as you are iterating on an object and wants functionality similar as such as array.

new Vue({
  el: '#app',
  data : {
    CareerLevel : {
    "CLLevel":
    {
        "13":
        {
            "Role":["Community Operations New Associate"]
        },
        "12":
        {  
            "Role":["Junior SME","Cross-Skilled Associate","Incubation\/Special Project Associate","Quality Auditor","Trainer","System Developer Associate","Junior SME","System Developer"]
        },
        "11":
        {
            "Role":["Jr. Team Lead\/ Senior SME","Market-Vetical SME","Senior Quality Auditor\/Analyst","Senior Trainer","Policy Analyst","System Developer Analyst","R&C Analyst","policy analyst"]
        },
        "10":
        {
            "Role":["Team Lead","Quality Jr Team Lead","Training Jr Team Lead","Policy Senior Analyst"," System Developer Team Lead"]},"9":{"Role":["Shift Lead"," Senior Team Lead","Quality Lead","Policy Lead","Change Management Lead","R&C Specialist","Training Lead"]
        },
        "8":
        {
            "Role":["Community Operations Market Lead","Local\/Site QTP Lead","Mobilization Lead","Service Management Lead","Global System Developer Lead"," Business Excellence Associate Manager"]
        }
    }
}
  },
  
  computed : {
    firstObj : function(){
      for (var key in this.CareerLevel.CLLevel) {
        if (this.CareerLevel.CLLevel.hasOwnProperty(key)) {
            return this.CareerLevel.CLLevel[key]
        }
        break;
      }
    }
  }
});
<div id="app">
 <a href="#">{{firstObj}}</a>
  <ul>
    <li>
      <a href="#">Grand Child</a>
    </li>
  </ul>
</div>

PS : This will render CLLevel with key 8 as you are using object and they are unordered in nature, no matter how you insert them in object they come out unordered, if you want CLLevel with key 13 to appear than you will have no other choice than to use array as arrays maintain order.

Leave a comment