Skip to content
Advertisement

How to number specific array items if they meet specific condition in Vue JS?

Let’s say I have an array of objects like below in my vue state:

[
 {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 displaying in a list. What I want to display on my web page is like below:

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

From example above, I think it’s quite clear what I want to achieve. What is the simplest way to achieve this in vue?

Advertisement

Answer

You can use Array.map to iterate over all array elements and generate your desired result

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)
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement