javascript 如何创建 JSON 列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14109191/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 20:44:17  来源:igfitidea点击:

How to create a JSON list?

javascriptjqueryjsonasp.net-mvc-3

提问by User_MVC

I have to form a JSON object like

我必须形成一个 JSON 对象,如

var SelectedRows=   {
        "item1":{"id":"1","name":"jhon","phone":"6699"},
        "item2":{"id":"2","name":"Aron","phone":"7799"},
        "item2":{"id":"3","name":"Iyan","phone":"8899"},
        }

On check box click event, I need to add the grid row values to the JSON list. I am trying with this code:

在复选框单击事件中,我需要将网格行值添加到 JSON 列表中。我正在尝试使用此代码:

var SelectedRows={};

$(this).delegate(":checkbox", "click", function() {        
    var j=0;
    var item=[];
    SelectedRows[item]={};        *//I guess this line creating problem*     
    $(this).closest("tr").find("td:visible").each(function(){            
        var key=headerRow[j]["i"];            
        if(j == 0)
        {              
        }
        else
        {   
            SelectedRows[item][key]=$(this).text(); 
        }
        j=++j; 
     });

After multiple checkbox click events happening,SelectedRowscontains only last click event data.

多个复选框单击事件发生后,SelectedRows仅包含最后一次单击事件数据。

How get all the checkboxes click events data?

如何获取所有复选框点击事件数据?

回答by Anshu

You can create an json array like this

你可以像这样创建一个json数组

var SelectedRows=   [
    item1:{id:"1",name:"jhon",phone:"6699"},
    item2:{id:"2",name:"Aron",phone:"7799"},
    item2:{id:"3",name:"Iyan",phone:"8899"}
]

回答by Rajat Singhal

replace var item[];by var item = 'item'+(j+1);and result should like..

替换var item[];var item = 'item'+(j+1);,结果应该是..

var SelectedRows=   {
    "item1":{"id":"1","name":"jhon","phone":"6699"},
    "item2":{"id":"2","name":"Aron","phone":"7799"},
    "item2":{"id":"3","name":"Iyan","phone":"8899"},
    }

回答by User_MVC

I done like this. it is displaying exactly above format.

我是这样做的。它正在显示完全高于格式。

var SelectedRows=[];
var rowCount=1;

Used extra count variable to from item1, item2, item3 etc..

使用额外的计数变量来自 item1、item2、item3 等。

    $(this).delegate(":checkbox", "click", function() {
        var j=0;
        var item={};    
            $(this).closest("tr").find("td:visible").each(function(){
               var key=headerRow[j]["i"];
                   if(j == 0){ }
                   else {
                          item[key]=$(this).text();
                        }
               j=++j; 
            });
            SelectedRows["item"+rowCount]=item;
            rowCount=++rowCount;
  });