so I have this array to help me with my input select options
Input select:
<select id="example-select"></select>
And the array with the options
const array_axis = ['2015', '2016', '2017', '2018', '2019', '2020'];//these are the options of my input select
This is how I use that array as options for my input select:
var select = document.getElementById("example-select");
for (index in array_axis) {
select.options[select.options.length] = new Option(array_axis[index], array_axis[index]);
}
This is the array I want to work with using the input select
const data = [{
agrupacion: 'Hombre',
col2015: 26.4,
col2016: 28.7,
col2017: 25.7,
col2018: 23.7,
col2019: 22.7,
col2020: 26.4
}, {
agrupacion: "Mujer",
col2015: 26.8,
col2016: 29,
col2017: 27.1,
col2018: 24.7,
col2019: 24.4,
col2020: 27.3
}];
What I need is to be able to select an option(2015,2016,2017,2018,2019,2020) and remove all the other keys that don't match in my data array.
For example if I pick 2017 that matches the key "col2017" so remove every other key that was not selected and leave the array like this
const data = [{
agrupacion: 'Hombre',
name: 25.7
}, {
agrupacion: "Mujer",
name: 27.1
}];
or rather than removing everything that wasn't selected, I figured it would probably be easier to create a new array with the selected keys instead and this is what I've tried so far:
$("#example-select").change(function(){
var selection = 'col' this.value;
const selected = data.map(e => ({
name: e.agrupacion,
data: selection
}));
console.log(selected);
});
but my output is this:
[{
data: "col2017",
name: "Hombre"
}, {
data: "col2017",
name: "Mujer"
}];
Is there a way to achieve that?
CodePudding user response:
$("#example-select").change(function(){
var selection = 'col' this.value;
const selected = data.map(e => ({
agrupacion: e.agrupacion,
name: e[selection]
}));
console.log(selected);
});
Basically instead of using name: selection
use name: e[selection]