44

I have declared a JSON Object and added some key value pair in that like:

var obj  = {};

and added some data into it like:

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

But I want to add more key value pair in the same object, if I add key value pair same above mentioned then it replace the old one. So could any one please tell me how I can append data in the same JSON Object i.e. obj.

Spencer Wieczorek
  • 21,229
  • 7
  • 44
  • 54
MaxSteel
  • 513
  • 1
  • 4
  • 11

8 Answers8

76

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'
Dan Eastwell
  • 5,146
  • 4
  • 22
  • 34
scgough
  • 5,099
  • 3
  • 30
  • 48
  • This will result in an exception being thrown.It makes no sense to use `JSON.parse()` on an instantiated JavaScript object. – Pointy Feb 15 '15 at 15:57
  • Also `.push()` is an array method, and is not available for plain objects. – Pointy Feb 15 '15 at 15:58
  • 1
    you;'re right Pointy - i was hasty in my answer! Have updated with alternative (working) solution. ;-) – scgough Feb 15 '15 at 16:06
  • @Vishnu It has nothing to do with nodejs and should work same way in any environment. Please be more specific in your query. – Sandy Dec 19 '18 at 07:19
16

You can use dot notation or bracket notation ...

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

obj.another = "valuehere";
obj["3"] = "cc";
rfornal
  • 5,072
  • 5
  • 30
  • 42
10

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)
deHaar
  • 17,687
  • 10
  • 38
  • 51
sagar buddhi
  • 493
  • 5
  • 8
  • 2
    This is the best answer especially when you need to add a large object with multiple key value pairs to an existing object. – Thinking May 06 '20 at 10:46
5

Example code for json object:

    var user = {'user':'barney','age':36};
    user["newKey"] = true;
    console.log(user);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="lodash.js"></script>

for json array elements

Example code:

var users = [
  { 'user': 'barney', 'age': 36 },
  { 'user': 'fred',   'age': 40 }
];

users.map(i=>{i["newKey"] = true});

console.log(users);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="lodash.js"></script>
dpmemcry
  • 117
  • 1
  • 4
4

Hi I add key and value to each object

let persons = [
  {
    name : "John Doe Sr",
    age: 30
  },{
    name: "John Doe Jr",
    age : 5
  }
]

function addKeyValue(obj, key, data){
  obj[key] = data;
}
 

let newinfo = persons.map(function(person) {
  return addKeyValue(person, 'newKey', 'newValue');
});

console.log(persons);
o12d10
  • 800
  • 3
  • 17
  • 31
Manish
  • 13,047
  • 1
  • 12
  • 9
3

You can add more key value pair in the same object without replacing old ones in following way:

var obj = {};

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

obj["3"] = "cc";

Below is the code and jsfiddle link to sample demo that will add more key value pairs to the already existed obj on clicking of button:

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

var noOfItems = Object.keys(obj).length;

$('#btnAddProperty').on('click', function() {
    noOfItems++;
    obj[noOfItems] = $.trim($('#txtName').val());
    console.log(obj);
});

https://jsfiddle.net/shrawanlakhe/78yd9a8L/4/

nyedidikeke
  • 6,899
  • 7
  • 44
  • 59
shrawan_lakhe
  • 358
  • 2
  • 5
  • 22
3

Please try following simple operations on a json, insert/update/push:

var movie_json = {
                    "id": 100,
                 };

//to insert new key/value to movie_json
movie_json['name'] = 'Harry Potter';
console.log("new key: " + movie_json);

//to update a key/value in movie_json
movie_json['id'] = 101;
console.log("updated key: " +movie_json);

//adding a json array to movie_json and push a new item.
movie_json['movies']=["The Philosopher's Stone"];
movie_json['movies'].push('The Chamber of Secrets');
console.log(movie_json);
0

possible duplicate , best way to achieve same as stated below:

function getKey(key) {
  return `${key}`;
}

var obj = {key1: "value1", key2: "value2", [getKey('key3')]: "value3"};

https://stackoverflow.com/a/47405116/3510511

sgajera
  • 146
  • 1
  • 9