JCam
JCam

Reputation: 614

Add or change a value of JSON key with jQuery or JavaScript

I have a JSON string(?) that I have returned from $.ajax() and named it data. Some of the values are empty and I need to add values to some of the keys and send it back to my PHP script.

I access the existing values by data.keyName. How do I add or change the values of certain keys in data?

This is what data looks like.

{
    "ID":"48",
    "userID":"0",
    "address":"750 North High Street",
    "city":"Columbus",
    "state":"OH",
    "zip":"43215",
    "lat":"39.977673",
    "lng":"-83.003357",
    "busNumber":"55",
    "isClaimed":"N",
    "whereFound":"",
    "busNum":"",
    "email":"",
    "fname":"",
    "lname":"",
    "comments":""
}  

Upvotes: 23

Views: 194631

Answers (8)

Serdar Karaca
Serdar Karaca

Reputation: 143

//We loop inside the array with "for"
for(let i = 0; i < _arrayJsonItems.length; i++)
{
    //First, we write the keys we want to delete
    delete _arrayJsonItems[i].KeyOne;
    delete _arrayJsonItems[i].KeyTwo;

    //Finally, we add new values ​​with the same key names.
    _arrayJsonItems[i].KeyOne = "NewValue";
    _arrayJsonItems[i].KeyTwo = "NewValue";
    
}

Upvotes: 0

Ren Lowsphere
Ren Lowsphere

Reputation: 7

You just set the data value like a normal javascript variable Ex:

data["userID"] = 4; // or data.userID = 4

Upvotes: 0

Gajender Singh
Gajender Singh

Reputation: 1313

var y_axis_name=[];

 for(var point in jsonData[0].data)
              { 
                y_axis_name.push(point);

              }

y_axis_name is having all the key name

try on jsfiddle

Upvotes: 0

dongjie
dongjie

Reputation: 81

It seems if your key is saved in a variable. data.key = value won't work.

You should use data[key] = value

Example:

data = {key1:'v1', key2:'v2'};

var mykey = 'key1'; 
data.mykey = 'newv1';
data[mykey] = 'newV2';

console.log(data);

Result:

{
  "key1": "newV2",
  "key2": "v2",
  "mykey": "newv1"
}

Upvotes: 8

epascarello
epascarello

Reputation: 207537

Just like you would for any other variable, you just set it

alert(data.ID);
data.ID = "bar";  //dot notation 
alert(data.ID);    
data.userID = 123456;
data["address"] = "123 some street"; //bracket notation

Upvotes: 4

sje397
sje397

Reputation: 41862

var temp = data.oldKey; // or data['oldKey']
data.newKey = temp;
delete data.oldKey;

Upvotes: 22

scheffield
scheffield

Reputation: 6787

data.userID = "10";

Upvotes: 0

cdhowie
cdhowie

Reputation: 169291

Once you have decoded the JSON, the result is a JavaScript object. Just manipulate it as you would any other object. For example:

data.busNum = 12345;
...

Upvotes: 50

Related Questions