Bravo
Bravo

Reputation: 1139

How to pass function parameter value as key in JSON object?

Assume I have the following function:

function create_unique_slug(database_slug_field, title) {
    var database_filter = {
        database_slug_field: title
    };
}

In this case, database_filter JSON object will contain key database_slug_field and its value will be the value of the passed parameter.

So, If I will call the function with the following input: create_unique_slug('slug_awesome', 'my awesome title');, JSON object will be the following:

{database_slug_field: 'my awesome title'}

What I want to achieve is get the JSON object as this:

{'slug_awesome': 'my awesome title'};

Thank you in advance

Upvotes: 2

Views: 3747

Answers (3)

Sebastian Nette
Sebastian Nette

Reputation: 7812

You have to use square brackets to tell javascript that you want to use the parameters value as key:

var database_filter = {};
database_filter[database_slug_field] = title;

Upvotes: 3

yvesmancera
yvesmancera

Reputation: 2925

Here's the modified function:

function create_unique_slug(database_slug_field, title) {
    var database_filter = {};
    database_filter[database_slug_field] = title;
    return database_filter;
}

If you want to print the object as JSON all you have to do is call JSON.stringify.

Upvotes: 5

CD..
CD..

Reputation: 74126

Like this:

function create_unique_slug(database_slug_field, title) {
    var database_filter = {};
    database_filter[database_slug_field] = title;
}

Upvotes: 1

Related Questions