node.jstypescriptloopback

How to sum nested objects and get a new object in typescript


I have 2 Objects Set_1 and Set_2. Inside their, two key are there in both Key_1 and Key_2. Inside those Key_1 and Key_2, there are Sub Keys(Sub Keys are same for Both Objects) which I want to add and want to create a new Object.

  "Set_1": {
  "Key_1": {
    "Sub_Key_1": 110,
    "Sub_Key_2": 72,
    "Sub_Key_3": 182
  },
  "Key_2": {
    "Sub_Key_1": 110,
    "Sub_Key_2": 72,
    "Sub_Key_3": 182
  }
}


"Set_2": {
"Key_1": {
    "Sub_Key_1": 50,
    "Sub_Key_2": 72,
    "Sub_Key_3": 112
},
  "Key_2": {
    "Sub_Key_1": 30,
    "Sub_Key_2": 40,
    "Sub_Key_3": 70
  }
}

I want output like below-

  "Set_3": {

  "Key_1": {
    "Sub_Key_1": 160,
    "Sub_Key_2": 144,
    "Sub_Key_3": 304
  },
  "Key_2": {
    "Sub_Key_1": 140,
    "Sub_Key_2": 112,
    "Sub_Key_3": 252
  }
}

Solution

  • const Set_1 = {
        "Key_1": {
            "Sub_Key_1": 110,
            "Sub_Key_2": 72,
            "Sub_Key_3": 182
        },
        "Key_2": {
            "Sub_Key_1": 110,
            "Sub_Key_2": 72,
            "Sub_Key_3": 182
        }
    };
    
    const Set_2 = {
        "Key_1": {
            "Sub_Key_1": 50,
            "Sub_Key_2": 72,
            "Sub_Key_3": 112
        },
        "Key_2": {
            "Sub_Key_1": 30,
            "Sub_Key_2": 40,
            "Sub_Key_3": 70
        }
    };
    
    const addSetsByKeys = (set1, set2) => {
        const output = {};
    
        Object.keys(set1).forEach(set1Key => {
            output[set1Key] = { ...set1[set1Key] };
        });
    
        Object.keys(set2).forEach(set2Key => {
            output[set2Key] = output[set2Key] || {};
            Object.keys(set2[set2Key]).forEach(set2SubKey => {
                output[set2Key][set2SubKey] = set2[set2Key][set2SubKey] + (output[set2Key][set2SubKey] || 0);
            });
        });
    
        return output;
    }
    
    const result = addSetsByKeys(Set_1, Set_2);
    console.log(result);