user

Shilpa

6 Mar 2022

JAVASCRIPT: How do I add another key to object?

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?

 

Comments

Mohamed Atef

6 Mar 2022

githubgithubgithub

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

Shilpa

6 Mar 2022

github

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

best answer

Your input is,

var obj = {"k1": "v1", "k2":"v2"};

With optimized solutions, you can use any approach as given below.

  1. If you don't know your key is existing in your json objects, Use this approach. Using brackets for new key, assign your values. It will automatically determine keys dynamically.
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