简体   繁体   English

用另一个 -Javascript 替换一个对象

[英]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.我知道这是一个非常常见的问题,但是我尝试了源代码,其中大多数提供了一些库、ES6 或本机 js 不支持的一些方法的答案。 I want to purely replace one object with another based on a condition- no ES6, no clone and no copy .我想根据条件纯粹用另一个对象替换一个对象 - 没有 ES6,没有clone也没有copy

in the below case: i want to get the value from subObj and replace them with the values in Obj1在下面的情况:我想从获得的价值subObj ,并在值替换它们Obj1

ex: key attributes "key2" and "key3" to be replaced from the values present in the subObj例如:要从 subObj 中存在的值替换的键属性“key2”和“key3”

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() .您可以使用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 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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