Home > other >  Stripping out part of array value in Javascript
Stripping out part of array value in Javascript

Time:02-03

I have an array that I'm currently breaking down with the map function in order to only get the option index of the original array. This works, but now I'm wanting to strip this down and only get the first 2 numerical digits from that option index (or more specifically, anything in front of the '-' in that value)

What's the best way to strip out only those digits while mapping it the way I currently am?

var vm = 
new Vue({
  el: "#app",
  data: {
    options: [
      {id:100, option:"1 - John Doe"},
      {id:200, option:"2 - Jane Doe"}
    ]
  },
  methods: {
    getNames(){
      
      let names = this.options.map(option => {
        return {
          id: option.option
        }
      });
      
      console.log(names);
    }
  }
  
  })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<button @click="getNames()">TEST</button>
</div>

CodePudding user response:

You can edit your map callback to get the first part of the string:

let options =  [
  {id:100, option:"1 - John Doe"},
  {id:200, option:"2 - Jane Doe"}
];

let names = options.map(option => {
    let opt = option.option;
    id = opt.split(' - ')[0];
    return { id };
});

console.log(names);

CodePudding user response:

const names = this.options.map(option => {
    const text = option.option // Get raw text from 'option'
    const parts = text.split('-') // Split text string by the '-' (returns an array, E.g. ["1 ", " John Doe"])
    return parts[0] // The first element of 'parts' is the result you are looking for (note it is a string, not a number)
})
  •  Tags:  
  • Related