我有以下物件陣列
const mi_array = [{
agrupacion: "Total país",
col2015: '81.8',
col2016: '86.4',
col2017: '67.3',
col2018: '70.8',
col2019: '67.6'
},{
agrupacion: "otra cosa",
col2015: '90.8',
col2016: '67.4',
col2017: '39.3',
col2018: '50.8',
col2019: '95.6'
}];
我需要把它變成這樣的東西:
const new_array = [{
name: "Total país",
data: [81.8, 86.4, 67.3, 70.8, 67.6]
}, {
name: "otra cosa",
data: [90.8, 67.4, 39.3, 50.8, 95.6]
}];
我試過這個,但由于鍵 col2015 到 2019 上的值都是字串,它不能按預期作業
const result = mi_array.map(e => ({
name: e.agrupacion,
data: Object.values(e).filter(e => typeof e == 'number')
}))
console.log(result)
輸出:
[{
data: [],
name: "Total país"
}, {
data: [],
name: "otra cosa"
}]
我知道如果我能以某種方式將這些值轉換為數字,它會起作用,所以我試圖用這個來實作:
for(let key of Object.keys(mi_array)) mi_array[key] = mi_array[key]
console.log(mi_array);
但是我的輸出是:
[NaN, NaN]
另一種嘗試:
var result = Object.keys(mi_array).map(function(key) {
return [Number(key), mi_array[key]];
});
console.log(result);
另一個失敗的輸出:
[[0, {
agrupacion: "Total país",
col2015: "81.8",
col2016: "86.4",
col2017: "67.3",
col2018: "70.8",
col2019: "67.6"
}], [1, {
agrupacion: "otra cosa",
col2015: "90.8",
col2016: "67.4",
col2017: "39.3",
col2018: "50.8",
col2019: "95.6"
}]]
有沒有一種有效的方法來做到這一點?
uj5u.com熱心網友回復:
在與 映射后,您可以解構name并僅從其余值中獲取值。dataNumber
這種方法采用物件的原始順序。
const
mi_array = [{ agrupacion: "Total país", col2015: '81.8', col2016: '86.4', col2017: '67.3', col2018: '70.8', col2019: '67.6' }, { agrupacion: "otra cosa", col2015: '90.8', col2016: '67.4', col2017: '39.3', col2018: '50.8', col2019: '95.6' }],
result = mi_array.map(({ agrupacion: name, ...o }) => ({
name,
data: Object.values(o).map(Number)
}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
uj5u.com熱心網友回復:
const new_array = [];
for(let i = 0; i < mi_array.length; i) {
const new_obj = {"name":"", "data":[]};
for(const key in mi_array[i]) {
const num = Number(mi_array[i][key]);
if(isNaN(num)) {
new_obj.name = mi_array[i][key];
} else {
new_obj.data.push(num);
}
}
new_array.push(new_obj);
}
uj5u.com熱心網友回復:
你可以用它。
首先,映射陣列并獲取映射agrupacion的屬性和其余道具data并轉換為Number.
const newArr = mi_array.map(({agrupacion, ...props})=> ({
name:agrupacion,
data: [...Object.values(props).map(value => Number(value))]
}))
uj5u.com熱心網友回復:
const mi_array = [{
agrupacion: "Total país",
col2015: '81.8',
col2016: '86.4',
col2017: '67.3',
col2018: '70.8',
col2019: '67.6'
},{
agrupacion: "otra cosa",
col2015: '90.8',
col2016: '67.4',
col2017: '39.3',
col2018: '50.8',
col2019: '95.6'
}];
new_array = []
for (var i = 0; i < mi_array.length; i )
{
new_dict = {"Data": []}
for (item in mi_array[i])
{
x = parseFloat(mi_array[i][item])
if (!(!(!(x))))
{
new_dict["Name"] = mi_array[i][item]
}
else
{
new_dict["Data"].push(x);
}
}
new_array.push(new_dict);
}
console.log(new_array)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/478939.html
標籤:javascript 数组
