可变地为for循环中的另一个对象分配新的键/值对

时间:2015-06-10 20:20:42

标签: javascript

我有两个对象我希望'比较' mongo更新的密钥,以及发送的数据中的任何新密钥,我想在更新之前添加到旧文档:

我试过了:

var updateObj = date[0];
var keys = Object.keys(req.body);
//I wish to look at the difference between req.body and updateObj

for (i = 0; i < keys.length; i++) {
  updateObj[keys[i]] = req.body[keys[i]];  //for the keys in my req.body, updateObj
                                           //now has that corresponding key/value in it
}
console.log(updateObj);  //i get data[0] in the console, oh no

但是当我在后端记录updateObj时,我得到数据[0] :(

1 个答案:

答案 0 :(得分:0)

如果您只想更新新内容和更改内容,请执行以下操作:

&#13;
&#13;
var updateObj = data[0];
var keys = Objects.keys(req.body);
for (var i = 0; i < keys.length; i++){
    var currentKey = keys[i];
    //Check if the key exists in the old object
    if updateObj.hasOwnProperty(currentKey) {
      if (updateObj[currentKey] !== req.body[currentKey]) {
        updateObj[currentKey] = req.body[currentKey];
      }
    } else {
      // Otherwise just add the new key/value pair
      updateObj[currentKey] = req.body[currentKey];
    }
  }
&#13;
&#13;
&#13;

否则只需遍历你的req.body并将所有键/值分配给旧对象,这将覆盖旧属性。