How to rename JSON key

后端 未结 11 730
名媛妹妹
名媛妹妹 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:38

    1. Parse the JSON
    const arr = JSON.parse(json);
    
    1. For each object in the JSON, rename the key:
    obj.id = obj._id;
    delete obj._id;
    
    1. Stringify the result

    All together:

    function renameKey ( obj, oldKey, newKey ) {
      obj[newKey] = obj[oldKey];
      delete obj[oldKey];
    }
    
    const json = `
      [
        {
          "_id":"5078c3a803ff4197dc81fbfb",
          "email":"user1@gmail.com",
          "image":"some_image_url",
          "name":"Name 1"
        },
        {
          "_id":"5078c3a803ff4197dc81fbfc",
          "email":"user2@gmail.com",
          "image":"some_image_url",
          "name":"Name 2"
        }
      ]
    `;
       
    const arr = JSON.parse(json);
    arr.forEach( obj => renameKey( obj, '_id', 'id' ) );
    const updatedJson = JSON.stringify( arr );
    
    console.log( updatedJson );

提交回复
热议问题