如何以相关方式从JSON中提取多个KEY:VALUE对

时间:2017-02-24 17:50:04

标签: javascript jquery arrays json

我正在为每日活动创建可公开编辑的日志,其中用户可以修改表格中的某些输入(例如日期,时间,复选框和用户注释;但第一列的位置) " Day"是硬编码的,即" Day 1"," Day 2"等),然后可以通过Local Storage保存。以下是我目前桌面风格的一个示例:

      <div id="table" class="table-editable table-responsive table-bordered">
<span class="table-add glyphicon glyphicon-plus"></span>
<table class="table">
  <tr class="warning">
    <th>Day</th>
    <th>Date</th>
    <th>Time</th>
    <th>Yes/No</th>
    <th>Notes</th>
  </tr>

  <tr class="active">
    <td contenteditable="true">Day 1</td>
    <td contenteditable="true"><input id="date1" value="" type="date" name="date" onblur="dateConstruct(1)"></td>
    <td contenteditable="true"><input id="time1" value="" type="time" name="usr_time" onblur="timeConstruct(1)"></td>
    <td contenteditable="true">Y <input class="radioBut" type="checkbox" name="1" value="Yes"> / N <input class="radioBut" type="checkbox" name="2" value="No"></td>
    <td contenteditable="true"><input id="note1" value="" type="text" name="notes" onblur="noteConstruct(1)"></td>
    <td>
      <span class="table-remove glyphicon glyphicon-remove"></span>
    </td>
  </tr>

  <tr class="active">
    <td contenteditable="true">Day 2</td>
<td contenteditable="true"><input id="date2" value="" type="date" name="date" onblur="dateConstruct(2)"></td>
    <td contenteditable="true"><input id="time2" value="" type="time" name="usr_time" onblur="timeConstruct(2)"></td>
    <td contenteditable="true">Y <input class="radioBut" type="checkbox" name="1" value="Yes"> / N <input class="radioBut" type="checkbox" name="2" value="No"></td>
    <td contenteditable="true"><input id="note2" value="" type="text" name="notes" onblur="noteConstruct(2)"></td>
    <td>
      <span class="table-remove glyphicon glyphicon-remove"></span>
    </td>
  </tr>
 </table>
 </div>

这是我用来保存数据的代码,工作正常:

   var $TABLE = $('#table');
   var $SAVEIT = $('#save-btn');

    $SAVEIT.click(function () {

      var $rows = $TABLE.find('tr:not(:hidden)');
      var headers = [];
      var data = [];
      var VALue = [];
      var keeey = "uSTORE-A";

      var SETData = function(keeey, VALue) {   
       if (!keeey || !VALue) {return;}
       localStorage.setItem(keeey, VALue);
       alert("DATA SAVED! \nYou may now close your browser.");
      };

     // Get the headers (add special header logic here)
     $($rows.shift()).find('th:not(:empty)').each(function () {
      headers.push($(this).text().toLowerCase());
     });

     // Turn all existing rows into a loopable array
     $rows.each(function () {
      var $td = $(this).find('td');
      var h = {};

      // Use the headers from earlier to name our hash keys
      headers.forEach(function (header, i) {
      h[header] = $td.eq(i).text();   
     });

     data.push(h);
    });

   var uSAVE = JSON.stringify(data);

   SETData("uSTORE-B", uSAVE);

   });

之后,例如在第二天进行更多日志记录,此人可以通过以上代码从JSON中加载以前保存的数据,该数据保存在本地存储的浏览器中。保存的JSON看起来像这样(出于笔测试的目的,我通过&#39; 警告()&#39;显示给我自己:

    [{"day":"Day 1","date":"2017-02-24","time":"12:01","yes/no":"Y","notes":"Some notes"},{"day":"Day 2","date":"2017-02-25","time":"06:06","yes/no":"Y","notes":"Another day's notes"},{"day":"Day 3","date":"2017-02-26","time":"","yes/no":"N","notes":""},{"day":"Day 4","date":"2017-02-27","time":"22:00","yes/no":"Y","notes":"Notes for day after no notes"}]

因此,我能够正确地保存数据(作为JSON),以及加载数据(作为JSON)。但是,我一直无法弄清楚如何使用用户之前保存的数据重新填充表格。换句话说,我无法弄清楚如何将JSON键的值:值对返回到表中,以便用户可以从中断的地方继续。我已经尝试了几种方法,但最后仍然使用第一个键:值对填充列的所有值,而不是循环使用单独的值。我应该以不同于我的方式保存JSON吗?

提前感谢您提供的任何帮助,或任何指向正确方向的手指。

2 个答案:

答案 0 :(得分:0)

您应该能够使用带有迭代器的for循环遍历数组,然后使用for ... in循环遍历对象属性。当然,如果没有实际的表格结构,我是否正朝着正确的方向前进是很难的。这是一个例子......

我已编辑过包含您的表格结构。看起来你只需要将json数据推送到输入......

&#13;
&#13;
var json =  [{"day":"Day 1","date":"2017-02-24","time":"12:01","yes/no":"Y","notes":"Some notes"},{"day":"Day 2","date":"2017-02-25","time":"06:06","yes/no":"Y","notes":"Another day's notes"},{"day":"Day 3","date":"2017-02-26","time":"","yes/no":"N","notes":""},{"day":"Day 4","date":"2017-02-27","time":"22:00","yes/no":"Y","notes":"Notes for day after no notes"}];

$(document).ready(function() {
  var $table = $('table');
  
  // set table data
  genData($table);
});

function genData($table) {
  // loop through array of rows
  for(var i = 0; i < json.length; i++) {
    // create a new row
    var $row = createRow();

    // loop through cells
    for(var cellName in json[i]) {
      // create a new cell
      var $cell = $('<td></td>');
      
      var $div;
      var n = i + 1;
      
      // fill appropriate input
      switch(cellName) {     
        case "date":
          $div = createDate(json[i][cellName], n);
          break;
        case "time":
          $div = createTime(json[i][cellName], n);
          break;
        case "yes/no":
          $div = createCheckboxes(json[i][cellName]);
          break;
        case "notes":
          $div = createText(json[i][cellName], n);
          break;
        default:
          $div = createStatic(json[i][cellName]);
          break;
      }
      
      // append the input to the cell
      $cell.append($div);
      
      // append the cell to the row
      $row.append($cell);
    }
    
    // append the row to the table
    $table.append($row);
  }
}

// create date input
function createDate(val, n) {
  var $input = $('<input type="date" name="date" onblur="dateConstruct(' + n + ')">').attr('id', "date" + n).val(val);
  return $('<div></div>')
    .append($input);
}

// create time input
function createTime(val, n) {
  var $input = $('<input type="time" name="usr_time" onblur="timeConstruct(' + n + ')">')
    .attr('id', "time" + n)
    .val(val);
  
  return $('<div></div>')
    .append($input);
}

// create checkbox inputs
function createCheckboxes(val) {
  var yesInput = $('<input class="radioBut" type="checkbox" name="1" value="Yes">');
  var noInput = $('<input class="radioBut" type="checkbox" name="2" value="No">');
  
  if(val == "Y") {
    yesInput.attr('checked', 'checked');
  } else {
    noInput.attr('checked', 'checked');
  }
  
  return $('<div></div>')
    .append($('<span>Y </span>'))
    .append(yesInput)
    .append($('<span> / N</span>'))
    .append(noInput);
}

// create text input
function createText(val, n) {
  var $input = $('<input type="text" name="notes" onblur="noteConstruct(' + n + ')">')
    .attr('id', "notes" + n)
    .val(val);
  
  return $('<div></div>')
    .append($input);
}

// create static text
function createStatic(val) {
  var $div = $('<div></div>');
  $div.text(val);
  return $div;
}

function createRow() {
  return $('<tr class="active"></tr>');
}

function createCell(content) {
  return $('<td contenteditable="true"></td>').text(content);
}

// dummy functions to remove errors
function dateConstruct(n) {

}

function timeConstruct(n) {

}

function noteConstruct(n) {

}
&#13;
table, th, tr, td {
  border: 1px solid #000000;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="table" class="table-editable table-responsive table-bordered">
<span class="table-add glyphicon glyphicon-plus"></span>
<table class="table">
  <tr class="warning">
    <th>Day</th>
    <th>Date</th>
    <th>Time</th>
    <th>Yes/No</th>
    <th>Notes</th>
  </tr>
 </table>
 </div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

// Parse JSON string into object.
let data = JSON.parse(/* your data variable */);
let table = /* select your table element's tbody */;
updateTable(data, table);


const updateTable = (data, table) => {
  // Iterate over data array to output new rows.
  let rows = data.map((entry) => {
    // Create your element.
    let thisRow = document.createElement('tr');

    // Repeat this next segment for each 'td' element you need
    // you could loop it with a 'for in', but you can't count on loop order 
    // if you do it that way and would need to separate create and append
    // actions
    thisRow.appendChild(createTableCell('day', entry.day));
    thisRow.appendChild(createTableCell('date', entry.date));
    // etc...

    return thisRow;
  });

  // Append new rows
  for (let i = 0; i < rows.length; i++) {
    table.appendChild(rows[i]);
  }
}; 

const createTableCell = (key, value) => {
  // Create td element
  let cell = document.createElement('td');
  // Create textnode
  let content = document.createTextNode(value);
  // Add node to element.
  cell.appendChild(content);

  // Other common way to add options.
  cell.className = key + ' my-awesome-cell-class';

  return cell; 
};

document.createElement()