Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 698
Bravo Avatar asked Jul 30 '26 17:07

Bravo


2 Answers

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.

like image 171
yvesmancera Avatar answered Aug 01 '26 06:08

yvesmancera


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 image 23
Sebastian Nette Avatar answered Aug 01 '26 06:08

Sebastian Nette



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!