[英]remove non-selected keys from array of objects or create new array of objects with only selected value
所以我有這個數組來幫助我輸入選擇選項
輸入選擇:
<select id="example-select"></select>
以及帶有選項的數組
const array_axis = ['2015', '2016', '2017', '2018', '2019', '2020'];//these are the options of 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]);
}
這是我想使用輸入選擇處理的數組
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
}];
我需要的是能夠選擇一個選項(2015,2016,2017,2018,2019,2020)並刪除我的數據數組中不匹配的所有其他鍵。
例如,如果我選擇與鍵“col2017”匹配的 2017,則刪除所有其他未選擇的鍵並像這樣保留數組
const data = [{
agrupacion: 'Hombre',
name: 25.7
}, {
agrupacion: "Mujer",
name: 27.1
}];
或者不是刪除未選擇的所有內容,我認為使用選定的鍵創建一個新數組可能會更容易,這就是我迄今為止嘗試過的:
$("#example-select").change(function(){
var selection = 'col'+this.value;
const selected = data.map(e => ({
name: e.agrupacion,
data: selection
}));
console.log(selected);
});
但我的輸出是這樣的:
[{
data: "col2017",
name: "Hombre"
}, {
data: "col2017",
name: "Mujer"
}];
有沒有辦法做到這一點?
$("#example-select").change(function(){
var selection = 'col'+this.value;
const selected = data.map(e => ({
agrupacion: e.agrupacion,
name: e[selection]
}));
console.log(selected);
});
基本上不使用name: selection
使用name: e[selection]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.