admin管理员组

文章数量:1318156

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

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

Share Improve this question asked Jun 29, 2015 at 18:06 BravoBravo 1,1396 gold badges31 silver badges57 bronze badges 3
  • That's not JSON it's an object literal. – CD.. Commented Jun 29, 2015 at 18:10
  • yeah, it's json, not JSON, or maybe j.s.o.n. if you wanna be pedantic... – dandavis Commented Jun 29, 2015 at 18:22
  • Well JSON is an acronym (Java Script Object Notation) and all acronyms are uppercased so JSON is correct. You say FBI not fbi. – Abdelhak Commented Oct 4, 2018 at 14:44
Add a ment  | 

3 Answers 3

Reset to default 5

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;
}

本文标签: javascriptHow to pass function parameter value as key in JSON objectStack Overflow