I would like to transform values inside an object of an object. Something like this:
Initial object:
const studentDetails = {
'details1': {Name: "John", CountryName: "US", value: 1},
'details2': {Name: "David", CountryName: "AUS", value: 2},
'details3': {Name: "Bob", CountryName: "UK", value: 3},
};
Transformed object:
{
'details1': {Name: "John", CountryName: "US", value: 2},
'details2': {Name: "David", CountryName: "AUS", value: 3},
'details3': {Name: "Bob", CountryName: "UK", value: 4},
};
I did something like this already but could not figure it out
Object.fromEntries(Object.entries(studentDetails).map(([key,
value]) => [key, some data transformation on value]))
>Solution :
You can do something like this. We define a transformValue function which takes in the student details object and any transform function. Then applies the transform function on every value and returns the whole transformed details object.
const studentDetails = {details1: { Name: "John", CountryName: "US", value: 1 }, details2: { Name: "David", CountryName: "AUS", value: 2 }, details3: { Name: "Bob", CountryName: "UK", value: 3 }};
const transformValue = (details, transform) => {
return Object.entries(details).reduce((acc, [key, detail]) => {
acc[key] = {
...detail,
value: transform(detail.value)
}
return acc;
}, {});
};
console.log(transformValue(studentDetails, (val) => val + 1)); // Increments value
console.log(transformValue(studentDetails, (val) => val * val)); // Squaring values