2017-03-06 78 views
-1

我有一個(嵌套的)數據結構包含對象和數組。並嘗試發送數據表,但只顯示一個值。如何將嵌套的JSON數據設置爲數據表?

JSON數據:

{ 
"data": [{ 
    "name": "name1", 
    "value": "value1", 
    "list": [{ 
    "sname": "sname1", 
    "svalue": "svalue1" 
    }, { 
    "sname": "sname2", 
    "svalue": "svalue2" 
    }] 
}] 
} 

JSON數據通過使用Java通過URL獲得。

jQuery代碼:

var pk = $("#pk").val(); 
console.log(pk); 
url = "/register/search?id=" + pk; 
console.log(url); 
$('#largeTable').DataTable({ 
"ajax": url, 
"bDestroy": true, 
"columns": [{ 
    "data": "name" 
}, 
{ 
    "data": "value" 
}, 
{ 
    "data": "list.1.sname" 
}, 
{ 
    "data": "list.1.svalue" 
}, 
{ 
    "data": null, 
    "defaultContent": editview 
} 
] 
}); 

這可以通過使用list.1list.0

顯示第一或第二list值但我想在時間的兩個值。

+0

這是一個[複製和粘貼(https://stackoverflow.com/questions/42619683/how-to-get-a-specific-or-multiple-從四分之一小時前的問題中提取值或鍵從嵌套json)。 – halfer

+0

[如何從嵌套的json獲取特定或多個值(或鍵)]的可能重複(http://stackoverflow.com/questions/42619683/how-to-get-a-specific-or-multiple-values-或-key-from-nested-json) – halfer

回答

2

您的list在json數據結構中是一個數組。因此,您應該使用

list.forEach(function(element) { 
    //console.log(element); 
}); 

您可以創建一個對象並動態構建JSON並將其設置爲「columns」數組。

下面是一個例子:

// make an empty object 
var myObject = {}; 

// set the "list1" property to an array of strings 
myObject.list1 = ['1', '2']; 

// you can also access properties by string 
myObject['list2'] = []; 
// accessing arrays is the same, but the keys are numbers 
myObject.list2[0] = 'a'; 
myObject['list2'][1] = 'b'; 

myObject.list3 = []; 
// instead of placing properties at specific indices, you 
// can push them on to the end 
myObject.list3.push({}); 
// or unshift them on to the beginning 
myObject.list3.unshift({}); 
myObject.list3[0]['key1'] = 'value1'; 
myObject.list3[1]['key2'] = 'value2'; 

myObject.not_a_list = '11'; 
+0

但數據表列如何修復值 – user7646838

+0

也許它會有幫助:https://datatables.net/forums/discussion/32993/best-way-to-update-cell-in -ROW基於上數據功能於另一細胞 – Yaroslav