jQuery Array.map和Object.keys()来映射对象数组的键

时间:2018-06-09 01:04:53

标签: jquery arrays json object key

我在这里有一个JSON文件:https://next.json-generator.com/api/json/get/E1qcwkNxr

我想用它来创建一个表。使用jQuery我得到响应数组并映射一些值来构建我的表体单元格:

  private lazy var fetchedResultsController: NSFetchedResultsController<EarthquakeEntity> = {
    let managedObjectContext = appDelegate.persistentContainer.viewContext
    let fetchRequest: NSFetchRequest<EarthquakeEntity> = EarthquakeEntity.fetchRequest()
    let dateSortDescriptor = NSSortDescriptor(key: #keyPath(EarthquakeEntity.time), ascending: false)
    fetchRequest.sortDescriptors = [dateSortDescriptor]
    let frc = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: managedObjectContext, sectionNameKeyPath: frcKeyPath, cacheName: nil)
    frc.delegate = self

    return frc
  }()

我想用键做同样的事情,因为我想用这些数据构建thead单元格。有办法吗? var data = $.getJSON('https://next.json-generator.com/api/json/get/E1qcwkNxr', function (response) { // map JSON to local arrays and define local vars var rows = response.map(function (r) { return [ r.age, r.index, r.registered, r.balance, r.eyeColor ]; }); }); 记录对象中的所有键,如何只映射我想要使用的键?

2 个答案:

答案 0 :(得分:1)

要回答有关Runnable的问题,您需要针对已知集合进行过滤。

例如:

Object.keys

这是一个解决方案,我把它放在一起(它基于我在评论中发布的小提琴链接,但已清理完毕),它使用let keysToRender = ['index', 'age']; Object.keys(response[0]).filter(key => { return ~keysToRender.indexOf(key) }) 。就个人而言,我更喜欢map而不是map(针对此问题),因为开销略有减少。

小提琴:Sec 15.12.2.5

修改 这是一个根据回应维持秩序的小提琴(正如您在其他评论中提到的那样) - http://jsfiddle.net/x3p79jfs/

希望它有所帮助!

$.each
$.getJSON('https://next.json-generator.com/api/json/get/E1qcwkNxr', function(res) {
    // Extracts values from response
    const getModelFromKeys = (res, keys) => {
        return res.map(item => {
            return keys.map(key => {
                return item[key];
            });
        });
    };

    // Build template to append
    const buildTableFromModel = (header, body) => {
        let reducer = (arr, func, acc) => {
            return arr.reduce(func, acc);
        };

        let getTemplateCell = (template, item) => template + `<td>${item}</td>`;
        let getTemplateRow = (template, item) => template + `<tr>${reducer(item, getTemplateCell, ``)}</tr>`;
        
        return `
            <table><thead><tr>
            ${reducer(header, getTemplateCell, ``)}
            </tr></thead><tbody>
            ${reducer(body, getTemplateRow, ``)}
            </tbody></table>
        `
    };

    // Our expected set of keys to render (note first, last names which do not exist)
    let pii_table = ['age', 'index', 'first_name', 'last_name', 'registered', 'balance', 'eyeColor'];

    // Filter expected keys against ajax response
    // let filteredKeys = Object.keys(res[0]).filter(key => {
    //    return ~pii_table.indexOf(key);
    // });

    // Filter expected keys against ajax response
    let responseKeys = Object.keys(res[0]);
    let filteredKeys = pii_table.filter(key => {
        return ~responseKeys.indexOf(key);
    });

    // Build Table Model From Filtered Keys
    let firstTableModel = getModelFromKeys(res, filteredKeys);
    
    // Append table to Body
    document.body.innerHTML += buildTableFromModel(filteredKeys, firstTableModel);
});
td {
    padding: 3px;
    text-align: center;
}
thead {
    color: white;
    background-color: #777;
}
tr:nth-child(2n) {
    background-color: #ccc;
}

答案 1 :(得分:0)

我建议你使用$.each()而不是$.map()。像这样:

var rows = [];
$.getJSON('https://next.json-generator.com/api/json/get/E1qcwkNxr', function (response) {
  $.each(response, function(i, x){
    var obj = {};
    var s = ["age", "index", "registered", "balance", "eyeColor"];
    $.each(x, function(k, v){
      if(s.indexOf(k) >= 0){
        obj[k] = v;
      }
    });
    rows.push(obj);
  });
});

现在您将拥有一个包含键和值的干净的对象数组。然后,您可以使用它来构建表格。

var $table = $("<table>");
$("<thead>").appendTo($table);
$("<tr>").appendTo($("thead", $table));
$.each(rows[0], function(key, val){
  $("<th>").html(key).appendTo($("thead tr", $table));
});
var $tbody = $("<tbody>").appendTo($table);
$.each(rows, function(ind, row){
  var $trow = $("<tr>").appendTo($tbody);
  $.each(row, function (item){
    $("<td>").html(item).appendTo($trow);
  });
});

工作示例:https://jsfiddle.net/Twisty/xv4kzy8L/

<强>更新

如果您需要以特定排序显示该表,则可以使用您的键名数组来执行此操作。然后按特定顺序显示结果:

var headers = ["age", "index", "registered", "balance", "eyeColor"];
var $table = $("<table>");
$("<thead>").appendTo($table);
$("<tr>").appendTo($("thead", $table));
$.each(headers, function(key, val){
  $("<th>").html(val).appendTo($("thead tr", $table));
});
var $tbody = $("<tbody>").appendTo($table);
$.each(rows, function(ind, row){
  var $trow = $("<tr>").appendTo($tbody);
  $.each(headers, function (k, i){
    $("<td>").html(row[i]).appendTo($trow);
  });
});

希望有所帮助。