search

Home  >  Q&A  >  body text

How to number specific array items if specific condition is met in Vue JS?

Suppose I have an array of objects in my vue state as shown below:

[
 {name: "Daniel", default: false},
 {name: "Ross", default: true},
 {name: "Rachel", default: false},
 {name: "Joey", default: false}
 {name: "Monica", default: true}
 {name: "Gunther", default: true}
]

On my web page, all these names are already displayed in the list. What I want to display on the web page is as follows:

From the above example, I think it's pretty clear what I want to achieve. What is the easiest way to achieve this in vue?

P粉665427988P粉665427988238 days ago483

reply all(2)I'll reply

  • P粉790187507

    P粉7901875072024-03-31 15:33:32

    Try using the compulated attribute. Check the code snippet below

    var app = new Vue({
      el: '#app',
      data() {
        return {
          list: [
           {name: "Daniel", default: false},
           {name: "Ross", default: true},
           {name: "Rachel", default: false},
           {name: "Joey", default: false},
           {name: "Monica", default: true},
           {name: "Gunther", default: true},
          ]
        };
      },
      computed: {
        getList() {
          let index = 1;
          return this.list.map(item => {
            return item.default ? `${item.name} - Default ${index++}` : `${item.name}`;
          });
        }
      }
    })
    sssccc
    

    reply
    0
  • P粉491421413

    P粉4914214132024-03-31 14:41:07

    You can use Array.map to iterate over all array elements and generate the result you want

    const data = [
      { name: "Daniel" , default: false },
      { name: "Ross"   , default: true },
      { name: "Rachel" , default: false },
      { name: "Joey"   , default: false },
      { name: "Monica" , default: true },
      { name: "Gunther", default: true }
    ];
    
    let defaultCount = 0;
    const res = data.map(item => `${item.name}${item.default? ` default ${++defaultCount}`:''}`)
    
    console.log(res)

    reply
    0
  • Cancelreply