在this.sources
中,我有这种数组数据:
this.sources = [
{
cost: 50000.5,
ids: { 1: "11112", 2: "1112", 3: "121212" },
months: { 1: "54548.5000", 2: "45.0000", 3: "510.5000" },
name: "test1"
},
{
cost: 12469134.5,
ids: { 1: "19689", 2: "19690", 3: "19691" },
months: { 1: "12345678.5000", 2: "0.0000", 3: "50.5000" },
name: "test2"
}
];
我需要的是替换所有情况下几个月内的所有数据(只需将4个小数位更改为2),然后返回具有相同结构的数组。
我尝试过的事情:
this.sources = this.fixDecimal(this.sources);
fixDecimal(source) {
for ( let elx in source ) {
let newsource = source[elx];
for ( let x = 0; x <= 11; x++ ) {
let result = newsource.months[x];
if (result) { if (result) { result.map(y => y.toFixed(2));}
}
}
return result;
}
但是,这根本不起作用。是否有任何简单的解决方案来固定以月为单位的小数并返回具有更改数据的同一数组?
答案 0 :(得分:2)
解决方案不起作用的原因是因为您将值作为字符串,并且不能在字符串上使用for(let i=0; i<dataset.length;i++){
let months = {};
// Instead of looping through a hardcoded amount, loop though all the keys:
Object.keys(dataset[i].months).forEach(function(key) {
months[key] = parseFloat(dataset[i].months[key]).toFixed(2);
});
dataset[i].months = months;
}
。以下代码段中的parseFloat可以缓解此问题:
dataset
这是假设您将结果保存在变量df1
Time Name Value
0 t1 Name1 3
1 t1 Name2 1
2 t1 Name3 5
3 t1 Name4 9
df2
Time Name Value
0 t2 Name1 3
1 t2 Name2 7
2 t2 Name3 5
3 t2 Name4 2
df3
Time Name Value
0 t2 Name2 7
1 t2 Name4 2
中,您可能需要对其进行一些调整。
答案 1 :(得分:1)
由于您所有的值都是字符串,并且在小数点分隔符后有4个位置,因此您可以仅slice()
除去最后两个字符:
const months = {
1: "54548.5000",
2: "45.0000",
3: "510.5000"
// ...
};
for (let m in months) {
months[m] = months[m].slice(0, -2);
}
console.log(months);
答案 2 :(得分:1)
此代码应执行所需的操作,而无需修改原始数组。 Slice将删除每个月的最后2个字符(您甚至可以在此处使用子字符串:v.substring(0, v.length - 2)
)
:
sources = [
{
cost: 50000.5,
ids: { 1: "11112", 2: "1112", 3: "121212" },
months: { 1: "54548.5000", 2: "45.0000", 3: "510.5000" },
name: "test1"
},
{
cost: 12469134.5,
ids: { 1: "19689", 2: "19690", 3: "19691" },
months: { 1: "12345678.5000", 2: "0.0000", 3: "50.5000" },
name: "test2"
}
];
console.log(sources.map(o => ({...o, months: Object.entries(o.months).reduce((a, [k,v]) => ({...a, [k]: v.slice(0, -2)}), {})})))
或者,您可以修改原始数组:
sources = [
{
cost: 50000.5,
ids: { 1: "11112", 2: "1112", 3: "121212" },
months: { 1: "54548.5000", 2: "45.0000", 3: "510.5000" },
name: "test1"
},
{
cost: 12469134.5,
ids: { 1: "19689", 2: "19690", 3: "19691" },
months: { 1: "12345678.5000", 2: "0.0000", 3: "50.5000" },
name: "test2"
}
];
sources.forEach((o, i) => sources[i].months = Object.entries(o.months).reduce((a, [k,v]) => ({...a, [k]: v.slice(0, -2)}), {}))
console.log(sources)