Add or change a value of JSON key with jquery or javascript

前端 未结 6 1657
有刺的猬
有刺的猬 2020-12-08 05:09

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

相关标签:
6条回答
  • 2020-12-08 05:43

    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;
    ...
    
    0 讨论(0)
  • 2020-12-08 05:45

    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"
    }
    
    0 讨论(0)
  • 2020-12-08 05:53

    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
    
    0 讨论(0)
  • 2020-12-08 05:54
    var temp = data.oldKey; // or data['oldKey']
    data.newKey = temp;
    delete data.oldKey;
    
    0 讨论(0)
  • 2020-12-08 05:57
    data.userID = "10";
    
    0 讨论(0)
  • 2020-12-08 06:01
    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

    0 讨论(0)
提交回复
热议问题