2017-01-16 29 views
-3

我有这样更改对象的属性基于可变

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

我希望能够改变基于变量值的属性名称的对象。 如果变量是“秒”,它应该改变属性秒到任何我想要的。 我已经试过一些方法...

object[theVariable] = "new second"; 

将属性的值更改为这个

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

object.theVariable = "new second"; 

将创建一个新的像这样的财产

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

这些方法都不能更改属性“第二”到“新的第二”时,“第二”被存储在变量“theVariable”

期望的结果:

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

这怎么可能做了什么?

+0

@melpomene:好像是OP希望的关键,更换 –

+0

您的代码不你想要什么,我没有看到问题。 –

+2

[change property name](http://stackoverflow.com/questions/8483425/change-property-name) – melpomene

回答

1

如果我的理解正确,您想要更改对象中属性的名称。这应该工作。通过括号标记

object.new_second = object.second; 
delete object.second 
-2

使用属性访问:

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);

+0

这不会将“second”更改为“new第二”。这只是取代价值 – Koiski

+0

@Koiski - 你是说你想让代码明白新属性的名称是“new”+ <旧属性的名称>',删除旧属性并设置新属性? – Igor

+0

@Igor查看更新后问题中的“所需结果”。 – melpomene

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);

+0

@Koiski更新回答! – Weedoze