Please help me transform the object. I have an object of the form
const object = {
2021: {
"13.0": { data: {} },
"13.1": { data: {} },
"17.0": { data: {} },
"17.1": { data: {} },
},
2022: {
"13.0": { data: {} },
"13.1": { data: {} },
"17.0": { data: {} },
"17.1": { data: {} },
},
};
If the number ends with ".0", then I need to change the number to a format without zero at the end of the number. The result should be an object of the form
const obj1 = {
2021: {
"13": { data: {} },
"13.1": { data: {} },
"17": { data: {} },
"17.1": { data: {} },
},
2022: {
"13": { data: {} },
"13.1": { data: {} },
"17": { data: {} },
"17.1": { data: {} },
},
};
I wrote the following code
const obj1 = {};
for (let year in object) {
obj1[year] = object[year];
for (let number in object[year]) {
const keyOk = number.endsWith('.0')
? number.slice(0, number.length - 2)
: number;
obj1[year][keyOk] = object[year][number];
if (number.endsWith('.0')) {
delete object[year][number];
}
}
}
This code works, but it seems to me that this option is not the most beautiful in terms of execution. Please tell me how else can I do this? Thank you
3
Answers
You can parse each key as a number (using
parseFloat(x)
or+x
) and assign that as the key of the new object. This will remove ".0", ".00", etc from the key.Output:
To remove unnecessary zeros, you can parse the string with
parseFloat()
,More description can be found here
For your situation, you can use parseFloat on the keys and then turn them into strings to get rid of any unnecessary decimal points. If the data structure stays the same, you can simply use the following code: