Home > Back-end >  How to number specific array items if they meet specific condition in Vue JS?
How to number specific array items if they meet specific condition in Vue JS?

Time:04-15

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?

CodePudding user response:

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)

CodePudding user response:

Try using computed property. Check the below code snippet

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}`;
      });
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<template>
 <ul>
  <li v-for="(item, index) in getList" :key="index">
  {{item}}
  </li>
 </ul>
</template>
</div>

CodePudding user response:

You can try this:

let defaultCount = 0;
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 },
].map((el) => {
  if (el.default) {
    defaultCount  ;
    return {
      ...el,
      defCount: defaultCount,
    };
  } else {
    return {
      ...el,
      defCount: null,
    };
  }
});

console.log(data);

<li v-for="(item) in array" :key="item.name">
{{`${item.name}${item.defCount? ` - Default ${item.defCount}`:''}`}}
</li>
  • Related