如何在jquery中将json字符串转换为对象 [英] How to convert json string to object in jquery
问题描述
大家好,
我的代码如下:
var controlNameAndValues = [
{controlName:'txt1',controlValue:'yellow'},
{controlName:'txt2',controlValue:'blue'},
{controlName:'txt3',controlValue:'red'}
];
这很完美,但问题是现在我的controlNameAndValues是动态的。那么我如何将动态controlNameAndValues转换为像上面的硬编码值一样工作。上面的controlNameAndValues给出了具有值的对象列表,但动态生成的对象列表没有我想要的对象列表。你可以帮帮我吗。
我尝试过的事情:
//这是用于动态生成controlNameAndValue
$(input [type ='text'])。each(function(){
if($(this).attr(id)!= null){
var controlName = $(this).attr(id);
var controlValue = $('#'+ controlName +'')。val();
controlNameAndValues + ='{controlName:'+'\''+ controlName +'\' '+',controlValue:'+'\''+ controlValue +'\'}';
i ++;
if(i< $(输入[type ='text'])。length)
{
controlNameAndValues + =,;
}
}
});
controlNameAndValues + =];
controlNameAndValues = $ .par seJSON(JSON.stringify(controlNameAndValues));
Hi Guys,
I have code like this:
var controlNameAndValues = [
{ controlName: 'txt1', controlValue: 'yellow' },
{ controlName: 'txt2', controlValue: 'blue' },
{ controlName: 'txt3', controlValue: 'red' }
];
This works perfect but the issue is that now my controlNameAndValues is dynamic. So how can i convert the dynamic controlNameAndValues to work like the above hard coded value. The above controlNameAndValues gives list of objects which has values but the dynamically generated does not have object list like I wanted. Can you please help me out.
What I have tried:
//this is for dynamically generating controlNameAndValue
$("input[type='text']").each(function () {
if ($(this).attr("id") != null) {
var controlName = $(this).attr("id");
var controlValue = $('#' + controlName + '').val();
controlNameAndValues += '{ controlName:' + '\'' + controlName + '\'' + ',controlValue:' + '\'' + controlValue +'\'}';
i++;
if(i < $("input[type='text']").length)
{
controlNameAndValues += ",";
}
}
});
controlNameAndValues += "]";
controlNameAndValues = $.parseJSON(JSON.stringify(controlNameAndValues));
推荐答案
(input [type ='text'])。each(function(){
if(
("input[type='text']").each(function () {
if (
(this).attr(id)!= null){
var controlName =
(this).attr("id") != null) {
var controlName =
(this).attr(id);
var controlValue =
(this).attr("id");
var controlValue =
这篇关于如何在jquery中将json字符串转换为对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!