JavaScript 使用数组键/值对附加到对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15009119/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 23:09:05  来源:igfitidea点击:

JavaScript append to object using array key/value pair

javascriptjqueryarraysobject

提问by chris

I have an object that I build out dynamically example:

我有一个动态构建的对象,例如:

obj = {};
obj.prop1 = 'something';
obj.prop2 = 'something';
obj.prop3 = 'something';

With that I now have a need to take an item from an array and use it to define both the equivalent of "propX" and its value

有了这个,我现在需要从数组中取出一个项目并使用它来定义“propX”的等价物及其值

I thought if I did something like

我想如果我做了类似的事情

obj.[arr[0]] = some_value;

That, that would work for me. But I also figured it wouldn't the error I am getting is a syntax error. "Missing name after . operator". Which I understand but I'm not sure how to work around it. What the ultimate goal is, is to use the value of the array item as the property name for the object, then define that property with another variable thats also being passed. My question is, is how can I achieve it so the appendage to the object will be treated as

那,那对我有用。但我也认为我得到的错误不是语法错误。“. 运算符后缺少名称”。我明白,但我不知道如何解决它。最终目标是使用数组项的值作为对象的属性名称,然后使用另一个传递的变量定义该属性。我的问题是,我怎样才能实现它,以便对象的附属物将被视为

obj.array_value = some_variable;

回答by Denys Séguret

Remove the dot. Use

删除点。利用

obj[arr[0]] = some_value;

I'd suggest you to read Working with objectsfrom the MDN.

我建议您阅读来自 MDN 的使用对象

回答by Mike Hogan

You could try

你可以试试

obj[arr[0]] = some_value;

i.e. drop the dot :)

即放下点:)

回答by Marryat

You are nearly right, but you just need to remove the . from the line:

你几乎是对的,但你只需要删除 . 从行:

obj.[arr[0]] = some_value;

obj.[arr[0]] = some_value;

should read

应该读

obj[arr[0]] = some_value;

obj[arr[0]] = some_value;