-2

I have an object like this

{"first":["first 1"],"second":["second 1","second 2"],"third":["third 1", "third 2"]}

I want to be able to change a property name based on a variable value. If the variable is "second" it should change the property second to whatever i want. I have tried some methods...

This

object[theVariable] = "new second";

Will change the value of the property to this

{"first":["first 1"],"second":"new second","third":["third 1", "third 2"]}

And this

object.theVariable = "new second";

Will create a new property like this

{"first":["first 1"],"second":["second 1","second 2"],"third":["third 1", "third 2"],"theVariable":"new second"}

None of these methods change the property "second" to "new second" when "second" is stored in the variable "theVariable"

Desired result:

{"first":["first 1"],"new second":["second 1","second 2"],"third":["third 1", "third 2"]}

How can this be done?

Koiski
  • 568
  • 2
  • 8
  • 23

3 Answers3

1

If I'm understanding correctly, you want to change the name of a property in your object. This should work.

object.new_second = object.second;
delete object.second
Austin
  • 1,291
  • 10
  • 19
1

var obj = {"first":["first 1"],"second":["second 1","second 2"],"third":["third 1", "third 2"]};

var theVariable = "new second";

obj[theVariable] = obj.second;
delete obj.second;

console.log(obj);
Weedoze
  • 13,683
  • 1
  • 33
  • 63
-2

Use property access through bracket notation:

    var obj = {
      "first":["first 1"],
      "second":["second 1","second 2"],
      "third":["third 1", "third 2"]
    };
    console.log(obj);
    var propNameVariable = "second";
    obj[propNameVariable] = "new second";
    console.log(obj);
Igor
  • 15,833
  • 1
  • 27
  • 32
  • this does not change "second" to "new second". This just replaces the value – Koiski Jan 16 '17 at 14:55
  • @Koiski - are you saying that you want the code to understand that the name of a new property is `"new " + `, delete the old property and set the new property? – Igor Jan 16 '17 at 15:03