How to remove space in keys of a JSON object

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

I have an output like below:

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


        
相关标签:
3条回答
  • 2020-12-12 07:16
    • Use Object.keys to get all keys of the object
    • Use String#replace to replace character from String

    var obj = {
      "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%"
      }]
    };
    
    Object.keys(obj).forEach(function(key) {
      var replaced = key.replace(' ', '');
      if (key !== replaced) {
        obj[replaced] = obj[key];
        delete obj[key];
      }
    });
    console.log(obj);

    Note: Only single occurrence of space is considered, RegEx could be used if space occurrence is more than once!

    0 讨论(0)
  • 2020-12-12 07:19

    Loop in each keys of the json, then parse.

    try regexp

    var word = "New Classroom"
    word = word.replace(/\s/g, '');
    console.log(word)

    0 讨论(0)
  • 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);

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