user1234
user1234

Reputation: 3159

replace one object with another -Javascript

I'm aware this muct a very common question, however I tried sources and most of them provide answers with some libraries, ES6 or some methods that native js does not support. I want to purely replace one object with another based on a condition- no ES6, no clone and no copy.

in the below case: i want to get the value from subObj and replace them with the values in Obj1

ex: key attributes "key2" and "key3" to be replaced from the values present in the subObj

Obj1 = {
"key1" : {values:[1, 2, 44, 505]},
"key2" : {values:[91, 25, 44, 5995]},
"key3" : {values:[1, 24, 44, 595]},
"key4" : {values:[17, 28, 44, 559]}
}

subObj = {

**"key2" : {values:[3, 3, 3, 444]},** // add this one 
**"key3" : {values:[1, 0, 0, 0]}**

}

so the output looks like:

Obj1 = {
"key1" : {values:[1, 2, 44, 505]},
**"key2" :{ values:[3, 3, 3, 444]},**
**"key3" : {values:[1, 0, 0, 0]},**
"key4" : {values:[17, 28, 44, 559]}
}

so far i have tried this:

  somefunc: function(condition) {

          if (condition) {
            Object.keys(Obj1).forEach(function(key) { Obj[key] = Obj1[key]});
            return Obj1;
          }
          return Obj;
        },

this does not work as expected, any help here? thx

Upvotes: 1

Views: 1593

Answers (3)

JBonAA
JBonAA

Reputation: 74

function merge(Obj1, subObj) {
    const result = {};

    Object.keys(Obj1).forEach((key) => {
        result[key] = Obj1[key]
    })

    Object.keys(subObj).forEach((k) => {
        if(result[k]){
            console.log('update')
            result[k] = subObj[k]
        } else {
            console.log("add")
            result[k] = subObj[k]
        }
    })

    console.log(result)
    return result
}

merge(Obj1, subObj)

Upvotes: 3

Adrian Brand
Adrian Brand

Reputation: 21628

This is what we use the spread operator for

const Obj1 = {
"key1" : {values:[1, 2, 44, 505]},
"key2" : {values:[91, 25, 44, 5995]},
"key3" : {values:[1, 24, 44, 595]},
"key4" : {values:[17, 28, 44, 559]}
}

const subObj = {

"key2" : {values:[3, 3, 3, 444]},
"key3" : {values:[1, 0, 0, 0]}

}

console.log({ ...Obj1, ...subObj });

Upvotes: 1

hawschiat
hawschiat

Reputation: 336

You can use Object.assign().

// ...

if (condition) {
    return Object.assign(Obj1, subObj);
}

// ...

Upvotes: 2

Related Questions