-1

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
  }
}

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

4 Comments

Can you please let me know the script based on the edited structure ?
@AbhishekMishra What do you mean by script ?, isn’t above code solving your issue ?
It is okay but my response structure is changed and when I am trying your code it is giving error. I have updated my structure in my question. Please help me on that. Thanks in advance and I'll mark your answer as accepted.
@AbhishekMishra From next time onwards please show your efforts to solve a problem if you post on stackoverflow.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.