Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Transform values inside object of object

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
   '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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading