Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I replace spaces in a JSON object keys dynamically using Javascript?

How can I replace the spaces in a JSON object's keys dynamically? For example, if I have the following object:

[{
    "FIRST NAME": "Philip",
    "LAST NAME": "Rivers",
    "NUMBER": "17",
    "GPA": "1.0",
    "OLD_FACTOR": "8",
    "NICENESS": "1"
}, {
    "FIRST NAME": "Peyton",
    "LAST NAME": "Manning",
    "NUMBER": "18",
    "GPA": "4.0",
    "OLD_FACTOR": "5000",
    "NICENESS": "5000"
}]

I want to be able to dynamically rename "FIRST NAME" and "LAST NAME" to "FIRST_NAME" and "LAST_NAME" respectively. Based on research so far, I have this function:

function replaceSpaces(data) {
    debugger;
    for (var i = 0; i < data.length; i++) {
        var obj = data[i];
        for (var key in obj) {
            var replacedKey = key.split(' ').join('_');
            data[i][obj] = replacedKey;
        }
    }

    return data;
}

The "data" parameter being passed in is an object that has already had JSON.parse ran on it prior to entering this function.

My issue with this code is that it's looping through the keys just fine, and assigning the proper replaced string to "replacedKey", but it's not assigning that to the original data object.

like image 726
the-nick-wilson Avatar asked Feb 09 '23 16:02

the-nick-wilson


1 Answers

Here's complete code using forEach.

The steps are same as Quentin has stated in his answer

  1. Copy the value
  2. Remove the key-value from the object
  3. Add new item with new value in the object

var arr = [{
  "FIRST NAME": "Philip",
  "LAST NAME": "Rivers",
  "NUMBER": "17",
  "GPA": "1.0",
  "OLD_FACTOR": "8",
  "NICENESS": "1"
}, {
  "FIRST NAME": "Peyton",
  "LAST NAME": "Manning",
  "NUMBER": "18",
  "GPA": "4.0",
  "OLD_FACTOR": "5000",
  "NICENESS": "5000"
}];


// Iterate over array
arr.forEach(function(e, i) {
  // Iterate over the keys of object
  Object.keys(e).forEach(function(key) {
    
    // Copy the value
    var val = e[key],
      newKey = key.replace(/\s+/g, '_');
    
    // Remove key-value from object
    delete arr[i][key];

    // Add value with new key
    arr[i][newKey] = val;
  });
});

console.log(arr);
document.getElementById('result').innerHTML = JSON.stringify(arr, 0, 4);
<pre id="result"></pre>

Strictly if the JSON is get in the form of String from server:

Replace the spaces by _ from the keys.

JSON.parse(jsonString.replace(/"([\w\s]+)":/g, function (m) {
    return m.replace(/\s+/g, '_');
}));
like image 53
Tushar Avatar answered Feb 11 '23 15:02

Tushar