Shilpa
6 Mar 2022
Javascript
My object literals:
{"k1": "v1", "k2":"v2"}
I want to add another key to the same object, how do I add another key {"k3": “v3”} to this object?
You can add a new object using
let obj = {"k1": "v1", "k2":"v2"};
obj.k3 = "v3";
or you can merge two objects using
let obj = {"k1": "v1", "k2":"v2"};
let obj2 = { k3: "v3" }
let obj3 = { ...obj, ...obj2 };
console.log(obj3);
//output
// {"k1": "v1", "k2":"v2", k3: "v3"}
Good luck
Using your 2nd approach,
let obj3 = { ...obj, ...obj2 };
Will other two objects destroy automatically? I just worried about performance if it is optimized solution or not when the code goes live?
Rakshit
6 Mar 2022
Best Answer
Your input is,
var obj = {"k1": "v1", "k2":"v2"};
With optimized solutions, you can use any approach as given below.
obj["k3"] = "v3";
2. If you are sure about key is already existing, you can use this approach.
obj.k3 = v3;
3. If you want to manage your object automatically with Object.assign method, use this approach. It is core utility provided using "Object" - itself. Visit here [Mozilla] to explore more about assign().
Object.assign(obj, {k3: "v3"});
The above solutions will work to answer your questions.
© 2024 Copyrights reserved for web-brackets.com