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

前端 未结 6 1686
有刺的猬
有刺的猬 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: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"
    }
    

提交回复
热议问题