How to remove space in keys of a JSON object

后端 未结 3 428
一整个雨季
一整个雨季 2020-12-12 06:48

I have an output like below:

output = {
  \"New Classroom\": [{
    \"Name\": \"Apple\",
    \"Age\": \"6\",
    \"Per         


        
3条回答
  •  执笔经年
    2020-12-12 07:25

    You can loop through the top-level property names in the object you receive, detect any with spaces, and remove the spaces. (You don't need to, they're perfectly valid property names, but you can if you want.)

    var output = { "New Classroom": [{"Name": "Apple","Age": "6","Percentage": "24.00%"},{"Name": "Orange","Age": "5","Percentage": "9.88%"},{"Name": "Green","Age": "2","Percentage": "27.27%"},{"Name": "Grey","Age": "6","Percentage": "12.63%"}]};
    var name, newName;
    // Loop through the property names
    for (var name in output) {
      // Get the name without spaces
      newName = name.replace(/ /g, "");
      // If that's different...
      if (newName != name) {
        // Create the new property
        output[newName] = output[name];
        // Delete the old one
        delete output[name];
      }
    }
    console.log(output);

    Note that using delete on an object can reduce the performance of subsequent property lookups. 99.99% of the time, that doesn't matter. If it matters in your case, create a new object rather than modifying it in place:

    var output = { "New Classroom": [{"Name": "Apple","Age": "6","Percentage": "24.00%"},{"Name": "Orange","Age": "5","Percentage": "9.88%"},{"Name": "Green","Age": "2","Percentage": "27.27%"},{"Name": "Grey","Age": "6","Percentage": "12.63%"}]};
    var name, newName;
    var newOutput = {};
    // Loop through the property names
    for (var name in output) {
      // Get the name without spaces
      newName = name.replace(/ /g, "");
      
      // Copy the property over
      newOutput[newName] = output[name];
    }
    console.log(newOutput);

提交回复
热议问题