How to rename JSON key

后端 未结 11 736
名媛妹妹
名媛妹妹 2020-11-27 12:46

I have a JSON object with the following content:

[
  {
    \"_id\":\"5078c3a803ff4197dc81fbfb\",
    \"email\":\"user1@gmail.com\",
    \"image\":\"some_imag         


        
11条回答
  •  星月不相逢
    2020-11-27 13:25

    If anyone needs to do this dynamically:

    const keys = Object.keys(jsonObject);
    
    keys.forEach((key) => {
    
          // CREATE A NEW KEY HERE
          var newKey = key.replace(' ', '_');
    
          jsonObject[newKey] = jsonObject[key];
          delete jsonObject[key];
       });
    

    jsonObject will now have the new keys.

    IMPORTANT:

    If your key is not changed by the replace function, it will just take it out of the array. You may want to put some if statements in there.

提交回复
热议问题