Search code examples
javascriptnode.jsvariablesconstants

Using a variable for a property name


When I try this code, I cannot give a const to "option_code" in an object.

const option_code = "option1211";
const product_code = "3344";
const size_code = "44"

var product_data = {
    option_code: size_code,
    quantity: "1",
    product_id: product_code,
}

I want a result like this (option code needs to change) =>

{ option1211:'44', quantity:'1', product_id:'3344' }

Is this possible ?


Solution

  • You're close, you just need to add square brackets around the key name:

    var product_data = {
        [option_code]: size_code,
        quantity: "1",
        product_id: product_code,
    }
    

    Otherwise, you can do the following:

    var product_data = {
        quantity: "1",
        product_id: product_code,
    }
    
    product_data[option_code] = size_code;