0

Is it possible to add nested objects together. I know Object.assign can merge two objects. For example:

const target = { a: 1, b: { c: 2, d: 3 } };
const source = { e: 7, b: { c: 1, d: 5 } };
const returnedTarget = Object.assign(target, source);

returnedTarget = { a: 1, b: { c: 1, d: 5 }, e: 7 }

But is there anyway to add variables C and D rather than overwriting them with the source?

An actual use case example:

[ 
    Character1: {
        kills: { value: 10.0, displayValue: "10" },
        deaths: { value: 5.0, displayValue: "5" }
    },
    Character2: {
        kills: { value: 20.0, displayValue: "20" },
        deaths: { value: 15.0, displayValue: "15" }
    },
]

//Expected Result: 

[
    Merged: {
        kills: { value: 30.0, displayValue: "30" },
        deaths: { value: 20.0, displayValue: "20" }
    }
]
T3rr11
  • 57
  • 9
  • 2
    You’d probably need [`Object.entries`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries) and [`reduce`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce). `Object.assign` isn’t the right tool here. If you want to merge nested objects, you’d also need to do it recursively. – Sebastian Simon Aug 25 '19 at 21:56
  • 1
    An issue is that `displayValue` is a *string* not a number, so you'll need to tweak the linked solution to cast the property value to a number first, so that addition works (and then turn it back to a string at the end) – CertainPerformance Aug 25 '19 at 21:59
  • That's not too bad, Just a quick parseInt() wrapper around the objects which define as isNaN() right? – T3rr11 Aug 25 '19 at 22:00
  • `parseInt` will round to an *integer*, you just want a number, so use `Number` – CertainPerformance Aug 25 '19 at 22:05

0 Answers0