Home > OS >  Transform values inside object of object
Transform values inside object of object

Time:11-03

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]))

CodePudding user response:

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

CodePudding user response:

A solution that doesn't involve Object.fromEntries or reduce. Just iterate over the object, adding updated objects to output, and then returning output.

const data={details1:{Name:"John",CountryName:"US",value:1},details2:{Name:"David",CountryName:"AUS",value:2},details3:{Name:"Bob",CountryName:"UK",value:3}};

const increment = (n) => n   1;
const decrement = (n) => n - 1;

function transform(data, prop, fn) {
  const output = {};
  for (const key in data) {
    output[key] = {
      ...data[key],
      [prop]: fn(data[key][prop])
    };
  }
  return output;
}

const update1 = transform(data, 'value', increment);
const update2 = transform(update1, 'value', decrement);

console.log(update1);
console.log(update2);

  • Related