Javascript 基于变量更改对象属性

Javascript 基于变量更改对象属性,javascript,object,Javascript,Object,我有一个这样的物体 {"first":["first 1"],"second":["second 1","second 2"],"third":["third 1", "third 2"]} {"first":["first 1"],"second":["second 1","second 2"],"third":["third 1", "third 2"],"theVariable":"new second"} 我希望能够基于变量值更改属性名称。 如果变量是“second”,它应该将sec

我有一个这样的物体

{"first":["first 1"],"second":["second 1","second 2"],"third":["third 1", "third 2"]}
{"first":["first 1"],"second":["second 1","second 2"],"third":["third 1", "third 2"],"theVariable":"new second"}
我希望能够基于变量值更改属性名称。 如果变量是“second”,它应该将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"]}
{"first":["first 1"],"second":["second 1","second 2"],"third":["third 1", "third 2"],"theVariable":"new second"}
当“second”存储在变量“theVariable”中时,这些方法都不会将属性“second”更改为“new second”

预期结果:

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

如何做到这一点?

如果我理解正确,您希望更改对象中属性的名称。这应该行得通

object.new_second = object.second;
delete object.second

通过括号表示法使用属性访问:

var obj={
“第一个”:[“第一个1”],
“第二个”:[“第二个1”,“第二个2”],
“第三”:[“第三个1”,“第三个2”]
};
控制台日志(obj);
var propNameVariable=“第二”;
obj[propNameVariable]=“新秒”;
控制台日志(obj)
var obj={“first”:[“first 1”],“second”:[“second 1”,“second 2”],“third”:[“third 1”,“third 2”];
var theVariable=“新秒”;
obj[theVariable]=obj.second;
删除obj.second;

控制台日志(obj)
@melpomene:看起来OP希望密钥被替换。您的代码符合您的要求,我看不出问题。可能是重复的。我想编辑属性名,而不是value@Koiski更新答案!这不会将“秒”更改为“新秒”。这只是取代了value@Koiski-您的意思是希望代码理解新属性的名称是
“new”+
,删除旧属性并设置新属性?