I have two objects obj1 & obj2.
when I merge with:
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);
I get the full obj2, and it dont have the key error_to_update_profile.
How I maintain the key of the first object that my second dont have?
CodePudding user response:
Use Object.prototype.hasOwnProperty()
to check whether your final objects has the property key error_to_update_profile
. The funtion returns true
which is prove that the merge worked perfectly fine as intended.
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"));
CodePudding user response:
You can change the order of what to write, i.e. whatever you put last will overwrite all previous entries { ...obj2, ...obj1 }
→ obj1
will overwrite obj2
if there are duplicate keys