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)"
user3845941
  • 175
  • 1
  • 14

2 Answers2

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

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • I would add `o.hasOwnProperty(k)`, just to make sure you are not doing anything to the parent object. – robbmj Jul 28 '14 at 21:41
  • @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. – adeneo Jul 28 '14 at 21:46
  • 1
    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 Jul 28 '14 at 21:48
  • @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. – adeneo Jul 28 '14 at 21:54
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"
Cᴏʀʏ
  • 105,112
  • 20
  • 162
  • 194
  • 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 } – user3845941 Jul 28 '14 at 21:32
  • I'm saying you don't need to replace the spaces. You can access properties with spaces in the names using the "array" notation. – Cᴏʀʏ Jul 28 '14 at 21:35
  • I actually am not referencing it. A plug is. I'm trying to get the data transformed for ngGrid in Angularjs – user3845941 Jul 28 '14 at 22:04