Ad
What Is The Best Way To Copy Only Certain Values From Every Object In Array Into Another Array?
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
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad