尝试在JavaScript函数中从JSON文件动态获取信息

尝试在JavaScript函数中从JSON文件动态获取信息,javascript,json,Javascript,Json,我找到了这个函数 <script> $(document).ready(function() { $('#container') .TidyTable({ columnTitles : ['Column A','Column B','Column C','Column D','Column E'], columnValues : [ ['1','1A','1B','1C','1D'

我找到了这个函数

<script>
$(document).ready(function() {
    $('#container')
        .TidyTable({
            columnTitles : ['Column A','Column B','Column C','Column D','Column E'],
            columnValues : [
                ['1','1A','1B','1C','1D','1E'],
                ['2','2A','2B','2C','2D','2E'],
                ['3','3A','3B','3C','3D','3E'],
                ['4','4A','4B','4C','4D','4E'],
                ['5','5A','5B','5C','5D','5E']
            ]
        });
});

</script>
我的问题是:

我可以动态地将这个JSON文件解析到上面的函数中吗?所以我想我有这样的东西:

<script>
$(document).ready(function() {
    $('#container')
        .TidyTable({
            columnTitles : ['Information 1','Information 2'],
            columnValues : [ //Something dynamic has to happen here for all entries
                ['information1', 'information2']
            ]
        });
});

</script>

我在这方面没有很好的经验,所以具体一点会对我有很大帮助。谢谢。

您应该能够使用jQuery的映射方法

var data = { "results": [
  {
    "information1": "Some info1",
    "information2": "Some info2"
  },
  {
    "information1": "Some info1",
    "information2": "Some info2"
  }
]}

// assumes keys are the same for every object in the array
var headers = $.map(data.results[0], function(v, k) { return k })

var values = [];
$.map(data.results, function(row) {
  values.push(
    $.map(row, function(v, k) {
      return v;    
    })
  );
});

console.log( headers ) // ['information1', 'information2']
console.log( values ) // [['Some info1', 'Some info2'], ['Some info1', 'Some info2']]
然后,只需在函数中使用新的数据格式:$'container'。TidyTable{columnTitles:headers,columnValues:values}

在这里拉小提琴:


.map上的文档:

是的,您可以。一种常见的解决方案是使用ajax请求检索json内容。通过响应,您可以解析json数据并在第二种情况下构建数组,它是一个矩阵,可以表示为一个数组os array。假设数组中每个对象的键都相同,这给我带来了困难。我从parse.com上的数据库导出JSON文件。如果键没有值,那么它们就不在JSON文件中,而我最后得到的表的列中有不正确的数据。此外,我希望数据按JSON文件中字母顺序以外的特定顺序排列。所以我的新问题是:我可以从JSON文件中获取特定信息并将其放入数组中吗。比如,只要求关键是信息的数据1?如果密钥不重要,请输入一个空字符串。我认为您完美地回答了我的问题,我将创建一个新问题。谢谢你,伙计。
var data = { "results": [
  {
    "information1": "Some info1",
    "information2": "Some info2"
  },
  {
    "information1": "Some info1",
    "information2": "Some info2"
  }
]}

// assumes keys are the same for every object in the array
var headers = $.map(data.results[0], function(v, k) { return k })

var values = [];
$.map(data.results, function(row) {
  values.push(
    $.map(row, function(v, k) {
      return v;    
    })
  );
});

console.log( headers ) // ['information1', 'information2']
console.log( values ) // [['Some info1', 'Some info2'], ['Some info1', 'Some info2']]