使用Javascript进行嵌套对象分配

时间:2017-07-23 21:18:18

标签: javascript object ecmascript-6 nested-loops



    var obj1 = {
      a: "imgood",
      b: {
        a1: {
          a2: "i shouldnt be here",
          b2: "imgood"
        },
        b1: "imgood"
      }
    };
    
    var obj2 = {
      b: {
        a1: {
          a2: "imgood"
        }
      }
    };
    console.log(Object.assign(obj1,obj2));




我希望更换a2但不会丢失其他属性。

以最简单,最短和最快的方式

4 个答案:

答案 0 :(得分:2)

这是一个在递归函数中带有for循环的解决方案:

function recursiveAssign(a, b) {
    if (Object(b) !== b) return b;
    if (Object(a) !== a) a = {};
    for (let key in b) {
        a[key] = recursiveAssign(a[key], b[key]);
    }
    return a;
}

var obj1 = {
  a: "imgood",
  b: {
    a1: {
      a2: "i shouldnt be here",
      b2: "imgood"
    },
    b1: "imgood"
  }
};

var obj2 = {
  b: {
    a1: {
      a2: "imgood"
    }
  }
};

console.log(recursiveAssign(obj1, obj2));
.as-console-wrapper { max-height: 100% !important; top: 0; }

或以功能性方式:

function recursiveAssign(a, b) {
    return Object(b) !== b ? b 
        : Object.keys(b).reduce ( (a, key) =>
            Object.assign(a, { [key]: recursiveAssign(a[key], b[key]) })
          , Object(a) === a ? a : {} );
}

var obj1 = {
  a: "imgood",
  b: {
    a1: {
      a2: "i shouldnt be here",
      b2: "imgood"
    },
    b1: "imgood"
  }
};

var obj2 = {
  b: {
    a1: {
      a2: "imgood"
    }
  }
};

console.log(recursiveAssign(obj1, obj2));
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:1)

您可以使用迭代和递归方法来分配值。

此提议会迭代源对象并在必要时创建新的目标属性,并在未找到嵌套对象时分配值。

function update(target, source) {
    Object.keys(source).forEach(function(key) {
        if (source[key] && typeof source[key] === 'object') {
            return update(target[key] = target[key] || (Array.isArray(source[key]) ? [] : {}), source[key]);
        }
        target[key] = source[key];
    });
}

var obj1 = { a: "imgood", b: { a1: { a2: "i shouldnt be here", b2: "imgood" }, b1: "imgood" } },
    obj2 = { b: { a1: { a2: "imgood" } } };

update(obj1, obj2);
console.log(obj1);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:0)

obj1.b.a1obj2.b.a1传递给Object.assign()

var obj1 = {
      a: "imgood",
      b: {
        a1: {
          a2: "i shouldnt be here",
          b2: "imgood"
        },
        b1: "imgood"
      }
    };
    
    var obj2 = {
      b: {
        a1: {
          a2: "imgood"
        }
      }
    };


Object.assign(obj1.b.a1, obj2.b.a1);

console.log(obj1);

答案 3 :(得分:0)

你的对象具有相似的结构,所以你可以通过一个非常简单的函数来完成这个技巧:



var obj1 = {
  a: "imgood",
  b: {
    a1: {
      a2: "i shouldnt be here",
      b2: "imgood"
    },
    b1: "imgood"
  }
};
    
var obj2 = {
  b: {
    a1: {
      a2: "imgood"
    }
  }
};

function changeA2 (obj) {
  obj['b']['a1']['a2'] = 'CHANGED';
  return obj;
}

console.log("new obj1: ", changeA2(obj1));
console.log("new obj2: ", changeA2(obj2));