简体   繁体   中英

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

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.

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;

Like this:

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

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