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
, notJSON
, or maybej.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
3 Answers
Reset to default 5Here'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
版权声明:本文标题:javascript - How to pass function parameter value as key in JSON object? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742029637a2416199.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论