close

how to add key value pair in the JSON object already declared

Hello Guys, How are you all? Hope You all Are Fine. Today we are going to learn how to add key value pair in the JSON object already declared in javascript. So Here I am Explain to you all the possible methods here.

Without wasting your time, Let’s start This Article.

how to add key value pair in the JSON object already declared ?

  1. how to add key value pair in the JSON object already declared ?

    add key value pair in the JSON object already declared Object assign copies one or more source objects to the target object. So we could use Object.assign here.

  2. add key value pair in the JSON object already declared

    add key value pair in the JSON object already declared Object assign copies one or more source objects to the target object. So we could use Object.assign here.

Method 1

Could you do the following:

obj = {
    "1":"aa",
    "2":"bb"
};


var newNum = "3";
var newVal = "cc";


obj[newNum] = newVal;



alert(obj["3"]); // this would alert 'cc'

Method 2

Object assign copies one or more source objects to the target object. So we could use Object.assign here.

Syntax: Object.assign(target, ...sources)

var obj  = {};

Object.assign(obj, {"1":"aa", "2":"bb"})

console.log(obj)

Summery

It’s all About this article. Hope all method helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you? Thank You.

Leave a Comment