0

I am trying to loop through an object that has properties and values. This object is created dynamically. My problem is that the dynamic object property is a string that contains spaces. Javascript object properties, however, can not contain spaces. How do I loop through this object and transform the property name so that spaces are taken out? Thanks for the help, here is the data below:

ANI: "4693584648"
Action Type: "IVR"
Brand: "Alpha Max Boost"
CSR Transfer: "No"
Call Date: "05/03/2014"
Call Status: "Complete"
Call Time: "15:59:36"
Customer ID: "114360"
DNIS: "9257324175"
First Name: "Isaac"
ID: "342262"
Last Name: "Torres"
OCO Action: "Early Cancel Save Sale Accepted (38.71)"
Order ID: "661438"
Recognition Method: "Automatic"
Status Group: "In Trial - Introduction (38.71)"
0

2 Answers 2

1

Objects can have spaces in the keys, if you still want to remove them, you'd do something like this

for (var k in o) {
    if (k.replace(/\s/g, '') != k && o.hasOwnProperty(k)) {
        o[k.replace(/\s/g, '')] = o[k];
        delete o[k];
    }
}

FIDDLE

If you have nested objects and arrays, you'd have to make it recursive

Sign up to request clarification or add additional context in comments.

4 Comments

I would add o.hasOwnProperty(k), just to make sure you are not doing anything to the parent object.
@robbmj - I generally don't see that as an issue, unless someone messed around with the Object prototype, but I'll add it anyway, it doesn't hurt anything and is just a few characters.
99/100 times you're safe to omit the hasOwnProperty check. It is just that 1% can be a real pain when your app is crashing in production.
@robbmj - That's true, I just generally leave it out, as for me it's 100/100 as I never mess with the Object prototype, so I know I don't have to use it, but I should get better at using it when posting code.
0

JavaScript objects certainly can have spaces in their property names. You have to change the setter/getter notation though:

// An array of your sample objects
var test = [{ ... }, { ... }, ...];

// Output the call status of the first one
console.log(test[0]['Call Status']); // should output "Complete"

3 Comments

The data above is dynamically created and can be an array of objects. So I need to do something like: for (var d in data) { //replace space in d }
I'm saying you don't need to replace the spaces. You can access properties with spaces in the names using the "array" notation.
I actually am not referencing it. A plug is. I'm trying to get the data transformed for ngGrid in Angularjs

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.