user image

Shilpa
Published in : 2022-03-06

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 Date : 2022-03-06

Best answers

46

Best answers

46

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 Date : 2022-03-06

Best answers

10

Best answers

10

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 Date : 2022-03-06

Best answers

34

Best answers

34

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.

Leave a comment

Join us

Join our community and get the chance to solve your code issues & share your opinion with us

Sign up Now

Related posts

How do I check if an array includes a value in JavaScript?
Publish date: 2022-02-13 | Comments: 2

Tag: Javascript

How to open URL in new tab & focus on it in Javascript?
Publish date: 2021-12-22 | Comments: 1

Tag: Javascript

How to move a div with its content to TinyMEC editor?
Publish date: 2022-02-11 | Comments: 0

Tag: Javascript

How to get audio input and audio output as one stream?
Publish date: 2022-02-13 | Comments: 1

Tag: Javascript

Adding an id number at the first index to an array of objects
Publish date: 2022-02-13 | Comments: 1

Tag: Javascript

Can we add a javascript or jQuery to the URL?
Publish date: 2022-03-05 | Comments: 2

Tag: Javascript

Coping plain text into form bug.
Publish date: 2022-02-11 | Comments: 1

Tag: Javascript