Ad

What Is The Best Way To Copy Only Certain Values From Every Object In Array Into Another Array?

- 1 answer

Because the Bootstrap Vue Form Select element uses the 'text' and 'value' values of objects in an array, I want to create a new array from an existing array with objects that each contain several values. I need to copy two of these values ('id' and 'msg') from every object in my existing array, and create objects of the same index in my new array, using the values from 'id' and 'msg' to populate their 'text' and 'value' values. What is the best way to do this?

This is what I came up with:

selectoptions(){
  var options = [];
  for (var i in this.proposals) {
    options[i] = { value: this.proposals[i].id, text: this.proposals[i].msg};
  }
  return options;
}

I am wondering if there is a better way to do this, possibly using Array.prototype.map.

Ad

Answer

If proposals is an object then do this:

const result = Object.keys(this.proposals).map((key) => ({
    value: this.proposals[key].id,
    text: this.proposals[key].proposal
}))

If proposals is an array

   const result = this.proposals.map((currentProposal) => ({
        value: currentProposal.id,
        text: currentProposal.proposal
    }))
Ad
source: stackoverflow.com
Ad