简体   繁体   中英

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

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.

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;

should read

obj[arr[0]] = some_value;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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