从另一个对象中省略具有某些深值的对象

时间:2019-05-17 12:56:47

标签: javascript node.js comparison javascript-objects

在更新集合中的资源时,我试图省略req.body数据,而对于集合中现有资源,仅使用null''字段。 / p>

但这也可以是通用的,这就是标题更通用的原因。

无论如何,请想象以下内容:

我们的数据库中有一个用户,其中包含以下数据:

{
  "firstName": "John",
  "lastName": "Doe",
  "address": {
    "Address1": "Random street 1",
    "City": "",
    "Country": null
  },
  "email": ""
}

用户正尝试使用以下数据更新现有资源:

{
  "firstName": "Mark",
  "address": {
    "Address1": "Random street 2",
    "City": "NY",
    "Country": "USA"
  },
  "email": "john.doe@mail.com"
}

更新的对象应如下所示:

{
  "firstName": "John", // Unchanged because propety value already exists
  "lastName": "Doe",
  "address": {
    "Address1": "Random street 1", // Unchanged because propety value already exists
    "City": "NY", // Updated because existing value is empty ("")
    "Country": "USA" // Updated because existing value is null
  },
  "email": "john.doe@mail.com" // Updated because existing value is empty ("")
}

我正在使用猫鼬,但我宁愿在基本的javascript对象级别上实现它

1 个答案:

答案 0 :(得分:1)

我不知道任何库,但是下面是使用递归的工作示例。

var oldObj = {
  "firstName": "John",
  "lastName": "Doe",
  "address": {
    "Address1": "Random street 1",
    "City": "",
    "Country": null
  },
  "email": ""
}

var newObj = {
  "firstName": "Mark",
  "address": {
    "Address1": "Random street 2",
    "City": "NY",
    "Country": "USA"
  },
  "email": "john.doe@mail.com"
}

updateObject(oldObj, newObj);


function updateObject(oldObj, newObj) {
  Object.keys(oldObj).forEach( key => {
    if (oldObj[key] && typeof oldObj[key] === 'object') {
      updateObject(oldObj[key], newObj[key]);
    } else {
      oldObj[key] = oldObj[key] || newObj[key];
    }
  });
}

console.log("Modified Obj: ", oldObj);

希望这对您有所帮助。