【问题标题】:merging objects delete initial keys合并对象删除初始键
【发布时间】:2022-01-13 12:18:22
【问题描述】:

我有两个对象 obj1 和 obj2。

当我合并时:

const obj1 = {
  error_to_retrieve: "teste",
  error_to_search_customer: "",
  error_to_sync_timezone: "",
  error_to_update_avatar: "",
  error_to_update_profile: "",
  error_to_validate_customer_token: "",
  expired_session: "",
  invalid_token: "",
  invalid_token_text: ""
}

const obj2 = {
  error_to_retrieve: "test",
  error_to_search_customer: "test",
  error_to_sync_timezone: "test",
  error_to_update_avatar: "test",
  error_to_validate_customer_token: "test",
  expired_session: "test",
  invalid_token: "test",
  invalid_token_text: "test"
}


const obj3 = {...obj1, ...obj2};

console.log(obj3);

我得到了完整的 obj2,但它没有 key error_to_update_profile。

我如何维护第二个对象没有的第一个对象的密钥?

【问题讨论】:

  • error_to_update_profile. 它对我有用。 ps,你的 obj1 和 obj2 上缺少逗号
  • 我在浏览器的控制台中运行它,我有 error_to_update_profil

标签: javascript object spread


【解决方案1】:

使用Object.prototype.hasOwnProperty() 检查您的最终对象是否具有属性键error_to_update_profile。该函数返回true,这证明合并按预期工作得非常好。

const obj1 = {
  error_to_retrieve: "teste",
  error_to_search_customer: "",
  error_to_sync_timezone: "",
  error_to_update_avatar: "",
  error_to_update_profile: "",
  error_to_validate_customer_token: "",
  expired_session: "",
  invalid_token: "",
  invalid_token_text: ""
};

const obj2 = {
  error_to_retrieve: "test",
  error_to_search_customer: "test",
  error_to_sync_timezone: "test",
  error_to_update_avatar: "test",
  error_to_validate_customer_token: "test",
  expired_session: "test",
  invalid_token: "test",
  invalid_token_text: "test"
};

const obj3 = { ...obj1, ...obj2 };

console.log(obj3.hasOwnProperty("error_to_update_profile"));

【讨论】:

    【解决方案2】:

    您可以更改写入内容的顺序,即最后输入的内容将覆盖所有先前的条目{ ...obj2, ...obj1 } → 如果有重复键,obj1 将覆盖 obj2

    【讨论】:

    猜你喜欢
    • 2021-08-20
    • 1970-01-01
    • 2019-01-28
    • 1970-01-01
    • 1970-01-01
    • 2011-10-09
    • 1970-01-01
    • 1970-01-01
    • 2010-09-25
    相关资源
    最近更新 更多