使用jQuery或JavaScript添加或更改JSON键的值

z9zf31ra  于 2023-10-17  发布在  jQuery
关注(0)|答案(8)|浏览(111)

我有一个JSONstring(?),我从$.ajax()返回并命名为data。有些值是空的,我需要向一些键添加值并将其发送回我的PHP脚本。
我通过data.keyName访问现有值。如何在data中添加或更改某些键的值?
这就是data的样子。

{
    "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":""
}
qhhrdooz

qhhrdooz1#

一旦您解码了JSON,结果就是一个JavaScript对象。就像操纵其他物体一样操纵它。举例来说:

data.busNum = 12345;
...
llycmphe

llycmphe2#

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

k3bvogb13#

如果你的密钥保存在一个变量中。data.key = value不工作。
使用data[key] = value
范例:

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

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

console.log(data);

测试结果:

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

i1icjdpr4#

就像你对其他变量一样,你只需要设置它

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

ff29svar6#

var y_axis_name=[];

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

              }

y_axis_name包含所有键名
试穿jsfiddle

jbose2ul

jbose2ul7#

你只需要像一个普通的JavaScript变量Ex一样设置数据值:

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

tvmytwxo8#

//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";
    
}

相关问题