Home > Back-end >  Filter attributes from an object
Filter attributes from an object

Time:01-25

Basically, I have one object that looks like this:

MainObject:{
   Object1: {
      Factory:{
         total: int
         today: int
      }
      Group:{
         total: int
         today: int
      }
      Sector:{
         total: int
         today: int
      }
   }
   Object2: {
      Factory:{
         total: int
         today: int
      }
      Group:{
         total: int
         today: int
      }
      Sector:{
         total: int
         today: int
      }
   }
.
.
.
}

How can I do a filter or mapping or something, that let me format it to something like:

MainObject:{
   Object1: {
      Variable1:{
         Variable2: int
   }
   Object2: {
      Variable1:{
         Variable2: int
      }
   }
.
.
.
}

Where Variable1 is a variable I can hardcode being it either Factory, Group or Sector and Variable2 is either total or today. Important to note that is an object, and not an array of objects.

CodePudding user response:

Here is a solution that will reduce the entries of the MainObject and keep only the specified variables for the deeper objects.

const myobj={MainObject:{Object1:{Factory:{total:1,today:2},Group:{total:3,today:4},Sector:{total:5,today:6}},Object2:{Factory:{total:7,today:8},Group:{total:9,today:10},Sector:{total:11,today:12}}}};

const Variable1 = 'Group';
const Variable2 = 'today';

const updatedObject = {
  MainObject: Object.entries(myobj.MainObject).reduce((main, [key, value]) => ({
    ...main,
    [key]: {
      [Variable1]: {
        [Variable2]: value[Variable1][Variable2]
      }
    }
  }), {})
}

console.log(updatedObject);

CodePudding user response:

You can create an array containing the keys of an object using a recursive function and the Object.keys method. Then, use the reduce method to reconstruct the object, only retaining the desired keys and values.

This may not be the solution to your problem, but it should provide you with a starting point.

function filterObj<T extends object>(
  obj: Partial<T>,
  keyToKeep: keyof T
): Partial<T> {
  return Object.keys(obj).reduce((acc, key) => {
    const value = obj[key as keyof T];
    if (key === keyToKeep) return { ...acc, [key]: value };
    else if (typeof value === 'object' && value !== null && value !== undefined)
      return { ...acc, [key]: filterObj(value as Partial<T>, keyToKeep) };

    return acc;
  }, {});
}
  • Related