简体   繁体   English

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

[英]JavaScript append to object using array key/value pair

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;

Remove the dot. 删除点。 Use 使用

obj[arr[0]] = some_value;

I'd suggest you to read Working with objects from the MDN. 我建议你阅读使用 MDN中的对象

You could try 你可以试试

obj[arr[0]] = some_value;

ie drop the dot :) 即放弃点:)

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM