简体   繁体   中英

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

You can use Object.assign() .

// ...

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

// ...
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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM