5

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.

3
  • 2
    data[i][replacedKey] = data[i][key]; Commented Oct 30, 2015 at 14:56
  • Are you actually asking about JSON? That is, are you interested in transforming the text content of a JSON document/string, or are you merely interested in working with JavaScript objects? Commented Oct 30, 2015 at 14:58
  • I'm interested in modifying the key name of the JavaScript object (if I'm understanding you correctly). I've already parsed it into the object, so I'm not interested in changing the string prior to that. Commented Oct 30, 2015 at 15:00

3 Answers 3

6

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, '_');
}));
Sign up to request clarification or add additional context in comments.

9 Comments

Ok I think I understand you guys now. One sec and I'll try to fit it into mine. (I was trying to avoid the .forEach function due to performance concerns).
@xboxremote Avoiding forEach? You should avoid for...in for better performance
My colleague mentioned he had found some articles saying .forEach performs slower. However, in researching myself, it does look like that might be false due to confusion in testing. At any rate, this worked perfectly (and I ended up using the .forEach). Thank you!
@DownVoter, at-least consider adding comment when down-voting a working and accepted answer. I'd be happy to improve answer.
@Tushar, strictly speaking about objects - it will be much faster to create new object with new keys rather then adding new key and deleting old one from original object.
|
4

You need to:

  • Copy the value
  • Delete the old property
  • Modify the correct object. (data[i][obj] will convert obj to a string and try to use it as a property name).

Such:

    for (var original_property in obj) {
        var new_property = original_property.split(' ').join('_');
        obj[new_property] = obj[original_property];
        delete obj[original_property]
    }

1 Comment

Slight error here: key.split should be original_property.split.
0

since it is JSON it is expected to come as string you could do it with a help of Regex.

var processedJson = yourJson.replace(/( +)(?=[(\w* *]*":)/g, "_");
var yourObj = JSON.parse(processedJson);

/( +)(?=[(\w* *]*":)/g will find all ocurances of within " ... ": which is a key on every JSON object.

5 Comments

Can you use .replace on an Object?
Right, I think Tushar is right here. I could do this earlier in my logic before I parse the JSON, but it wouldn't make sense in the context of my app. At this point in the app, I don't believe this would work.
regex works only with strings. but as I said JSON comes as string. or you however can use JSON.stringify() on every object in JS anytime you want
@Tushar when your JSON comes as string (from ajax) using Regex is a valid method, I don't see any reason why would I avoid it.
I might have been unclear in my original question, but I was looking to avoid any manipulation of the string equivalent, because I'm already past that in my app's logic. This function was designed to take an object, and not a string. Stringifying and parsing again would be unnecessary if I already have an object I can loop through. I definitely understand your proposal though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.