[英]Parsing from JSON file to JavaScript in a specific order
I have the following function: 我有以下功能:
$(document).ready(function() {
$('#container')
.TidyTable({
columnTitles : ['Name','Address','Age'],
columnValues : [
['Dan','Daneroad 1','19'],
['Ann','Annroad',''],
]
});
});
I have a JSON file with the following structure: 我有一个具有以下结构的JSON文件:
{ "results": [
{
"address" : "some address1"
"age" : "some age1"
"name" : "some name1"
},
{
"address" : "some address2"
"name" : "some name2"
}
]}
As you can see the order is alphabetic and not all objects contain the same amount of information. 如您所见,顺序是字母顺序的,并非所有对象都包含相同数量的信息。 Can I create an array that will replace columnValues, with arrays that have key/values in the order I want, and if a key is not present replace it with an empty string?
我是否可以创建一个数组,该数组将替换columnValues,而数组中的键/值按我想要的顺序排列,如果不存在键,则将其替换为空字符串? I imagine the array will look like this
我想阵列会像这样
[
['some name1', 'some address1', 'some age1'],
['some name2', 'some address2', '']
]
I am not that traversed in this area so please be specific thanks :) 我在这个领域还没有遍历,所以请特别感谢:)
Assuming you already know the property names you are looking for (because I assume they match the column titles), you can simply do something like this: 假设您已经知道要查找的属性名称(因为我假设它们与列标题匹配),则可以执行以下操作:
var array = [];
for(var i=0; i < original.results.length; i++) {
var subArray = [];
subArray.push(original.results[i].name || "");
subArray.push(original.results[i].address || "");
subArray.push(original.results[i].age || "");
array.push(subArray);
}
console.log(array);
Or, if you want to be more terse, you can do this in the body of the loop: 或者,如果您想更简洁,则可以在循环体内执行此操作:
array.push([original.results[i].address || "",
original.results[i].name || "",
original.results[i].age || ""]);
If you don't know the properties of the objects in results
then it's a little more tricky. 如果您不知道
results
对象的属性,那就有些棘手了。 You can use a for..in
loop to loop over all the properties, but the order won't be guaranteed. 您可以使用
for..in
循环for..in
所有属性,但是不能保证顺序。
you can use the function in bellow... 您可以在下面使用该功能...
function objToColumnValues(results, headers){
var values = results.map(function(resultItem){
var row = [];
headers.forEach(function(header){
row.push(resultItem[header] || '' );
});
return row;
});
return values;
}
you will use ... 您将使用...
//in var json is your json-string
var parsed = JSON.parse(json);
var colValues = objToColumnValues(parsed.results, ['name', 'address', 'age']);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.