0

I've got this object:

servicesSelected: {
  spw: {
    sku: "XYZ"
  }
}

I need to make it look like this:

servicesSelected: {
  XYZ: {
    sku: "XYZ"
  }
}

What I've done so far:

myVar = servicesSelected.spw.sku //stores "XYZ" as myVar

This is where I can't get it. The following doesn't work. I can't use regular dot notation because it doesn't support inserting variables, right?

newObject = ["servicesSelected"][myVar]sku[myVar]
fuzzybabybunny
  • 5,146
  • 6
  • 32
  • 58
  • 1
    possible duplicate of [JavaScript: Object Rename Key](http://stackoverflow.com/questions/4647817/javascript-object-rename-key) – Andy Jun 27 '14 at 11:16
  • ohhh... that worked. Thanks a bunch. I wasn't thinking along the lines of "renaming", but rather "re-arranging". – fuzzybabybunny Jun 27 '14 at 11:33

2 Answers2

0

Try this:

var newObject = new Object();
newObject["servicesSelected"][myVar]["sku"] = myVar;

Javascript supports object attribute querying with double square brackets, as well as dynamic generation of attributes. In this case, you can then query it with newObject.servicesSelected[myVar].sku.

Nzall
  • 3,439
  • 5
  • 29
  • 59
0

FYI this is the method that I ended up using:

myVar = servicesSelected.spw.sku // myVar is assigned "XYZ"

And then...

servicesSelected[myVar] = servicesSelected["spw"];

This created:

servicesSelected: {
  spw: {
    sku: "XYZ"
  },
  XYZ: {
    sku: "XYZ"
  }
}

The next step:

delete servicesSelected["spw"];

Created:

servicesSelected: {
  XYZ: {
    sku: "XYZ"
  }
}
fuzzybabybunny
  • 5,146
  • 6
  • 32
  • 58