How to number specific array items if specific condition is met in Vue JS?
P粉665427988
P粉665427988 2024-03-30 16:33:24
0
2
514

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:

  • Daniel
  • Ross - Default 1
  • Rachel
  • Joey
  • Monica - Default 2
  • Gunther - Default 3

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粉665427988
P粉665427988

reply all(2)
P粉790187507

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
P粉491421413

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)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template