提取KeyValue对,并使用jQuery将其转换为JSON(列和行)
我正在研究Asp.net MVC。 我想将Excel数据导入到我的一个网格中。 我使用ExpandoObject
(dynamic)读取Excel文件,然后将其转换为键/值对。 我想知道如何提取KeyValue对,并以JSON格式从该键/值对生成一个头和数据行。
数据将如下所示:
我想把这个KeyValue转换成Header和Row,如下所示:
[ {"CustomerName" : "Messi", "City":"Buenos Aires", "Country" :"Argentina"}, {"CustomerName" : "Ronaldo", "City":"Lisbon", "Country" :"Portugal"}, {"CustomerName" : "Persie", "City":"Amsterdam", "Country" :"Netherlands"}, {"CustomerName" : "Ronnie", "City":"London", "Country" :"England"} ]
我已经使用了以下jQuery代码片段,但它不起作用:
var arr = []; $.each(dataReceivedFromServer, function (i, data) { var d = data.Key; arr.push({ d: data.Value, }); });
如果我这样做,它显示我[{"d":"Messi"},{"d":"Buenos Aires"},{"d":"Argentina"}
等等…
简而言之,我想将Excel文件中的数据绑定到KendoUI
网格(所有的列都是dynamic的,因为用户可以select任何文件)。
有谁知道如何做到这一点?
更新#1:
@webkit – 请看下面的图像作为Console.log的输出
我强烈build议在收到数据之前对其进行转换,因为这样会更可靠。 但是,如果这是不可能的,并且可以保证数据集上有一些分组规则,则可以应用以下内容:
var customer = { //this transform asserts the key value collection will be in a groupable order transform: function(coll, groupBeginKey){ var result = []; var currentObject = {}; var size = coll.length; $.each(coll,function(idx,data){ //check if we are beginning var defined = (typeof(currentObject[data.Key]) !== 'undefined'); if(!defined && data.Key === groupBeginKey){ currentObject = {}; }else if((defined && data.Key === groupBeginKey)){ result.push(currentObject); currentObject = {}; } //set the property on the object currentObject[data.Key] = data.Value; //handle last if(idx >= size-1){ result.push(currentObject); } }); return result; } };
对于下面的数据集(为简单起见,我简化了它):
var data = [] data.push({ "Key": "CustomerName", "Value": "Paul"}); data.push({ "Key": "City", "Value": "Las Vegas"}); data.push({ "Key": "CustomerName", "Value": "George"}); data.push({ "Key": "Zip", "Value": "1234567"}); data.push({ "Key": "City", "Value": "New York"}); data.push({ "Key": "CustomerName", "Value": "Joe"}); data.push({ "Key": "City", "Value": "Omaha"});
断言客户可以从客户名到城市分组,您按以下方式使用它(它将包括具有邮政编码的客户):
var results = customer.transform(data,"CustomerName");
请在下面的jsfiddle中查看它的操作(查看debugging控制台中的输出):