本文介绍了将变量中的字符串作为javascript对象文字中的键传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我该怎么做?
objPrefix = btn.attr('data-objprefix'); //<button data-objPrefix="foo">
var sendData = {objPrefix : {"bar":"ccccc"}};
我希望输出
{"foo" : {"bar":"ccccc"}};
但它是
{"objPrefix" : {"bar":"ccccc"}}
推荐答案
当您使用文字符号 objPrefix
被视为键名本身而不是变量值 objPrefix
,而是尝试使用来设置基于变量值的对象的属性名称。所以尝试这种方式:
When you use the literal notation objPrefix
is considered as the keyname itself and not value of the variable objPrefix
, Instead try use bracket notation to set the property name for the object based on a variable value. So try this way:
var sendData = {};
sendData[objPrefix] = {"bar":"ccccc"};
你也可以使用jquery data-api来获取data-attribute的值,即
Also you can infact use jquery data-api to fetch the value of data-attribute i.e
objPrefix = btn.data('objprefix')
这篇关于将变量中的字符串作为javascript对象文字中的键传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!