MyDaftQuestions
MyDaftQuestions

Reputation: 4691

How to create an object with a parameter

I want to create an object dynamically. What I'd like to have is

function create(s){
    const obj = { 
        s : [1,2,3]
    }
}

create("hello");

This means my object would look like

{
    hello : [1, 2, 3]
};

Long term usage would mean my object would become

{
    football: [1,2,3],
    hockey: {},
    etc: []
}

I am unable to achieve this. Instead, the function create renders the variable name as the string, not the value of the variable. As such, the output is

{
    s : [1,2,3]
}

What do I need to do so I can create my object dynamically based upon the argument I pass in?

Upvotes: 1

Views: 150

Answers (2)

Unmitigated
Unmitigated

Reputation: 89179

You can use square brackets for a computed property name.

function create(s){
    const obj = { 
        [s] : [1,2,3]
    }
    return obj;
}

function create(s){
    const obj = { 
        [s] : [1,2,3]
    }
    return obj;
}
console.log(create("hello"));

Upvotes: 1

Ashish
Ashish

Reputation: 4330

since JavaScript object property names (keys) can only be strings or Symbols, when you write {temp: 1} here JS will automatically convert it to 'temp'.

To achieve dynamic keys You can do like this:

function create(s){
    const obj = { 
        [s] : [1,2,3]
    }
    return obj
}

const output = create("hello")
console.log(output)

Here I am using [] around the keys to treat the key as a variable and not string.

Upvotes: 0

Related Questions