循环对象

时间:2017-08-30 11:08:41

标签: javascript jquery html5

我循环一个对象并期望结果作为表的元素



var db = {
    "id": "8",
    "user_id": "24",
    "batchno": "367727",
    "ht_number": "jibhbu",
    "ht_taste": "uvyutvc",
    "pp_flavour": "ytv,yurtcrc,urt",
    "pp_fruit_batch": "cuyt,cytc,yt",
    "sl_flavour": "ouihyuigytvytc",
    "sl_appearance": "rtctr"
  },
  pp_ = '<table><tbody>';
for (var i in db) {
  if (db.hasOwnProperty(i)) {
    var js = db[i].split(',');
    for (var x in js) {
      if (i.startsWith('pp_')) {
        pp_ += '<tr><td>' + i + ' ' + x + ' : ' + js[x] + '</td></tr>';
      }
    }
  }
}
pp_ += '</tbody></table>';
document.write(pp_);
&#13;
&#13;
&#13; 我正在拆分带逗号的值,以便数组的每个索引位于1行(tr)

我能解决的是如何在同一级别(行)上放置具有相同索引的元素所以我可以使用

&#13;
&#13;
table, td {
border: 1px solid black;
}
&#13;
<table>
    <tbody>
        <tr>
            <td> pp_flavour 0 - its value </td>
            <td> pp_fruit_batch 0 - its value </td>
        </tr>
        <tr>
            <td> pp_flavour 1 - its value </td>
            <td> pp_fruit_batch 1 - its value </td>
        </tr>
        <tr>
            <td> pp_flavour 2 - its value </td>
            <td> pp_fruit_batch 2 - its value </td>
        </tr>
    </tbody>
</table>

<br>

<table>
    <tbody>
        <tr>
            <td> sl_favour 0 - its value </td>
            <td> sl_appearance 0 - its value </td>
        </tr>
        <tr>
            <td> sl_favour 1 - its value </td>
            <td> sl_appearance 1 - its value </td>
        </tr>
    </tbody>
</table>
&#13;
&#13;
&#13;

依旧......

4 个答案:

答案 0 :(得分:3)

你可以试着像这样索引数据库:

read()
var db = {
  "id": "8",
  "user_id": "24",
  "batchno": "367727",
  "ht_number": "jibhbu",
  "ht_taste": "uvyutvc",
  "pp_flavour": "ytv,yurtcrc,urt",
  "pp_fruit_batch": "cuyt,cytc,yt",
  "sl_flavour": "ouihyuigytvytc",
  "sl_appearance": "rtctr"
};

var prefixes = ["pp", "ht", "sl"];
var prefixedDb = {};
var result = "";

for (var i in db) {
  if (db.hasOwnProperty(i)) {
    var parts = i.split("_");
    var prefix = parts[0];

    if (prefixes.indexOf(prefix) === -1) continue;
    if (prefixedDb[prefix] === undefined) {
      prefixedDb[prefix] = {};
    }

    prefixedDb[prefix][parts.slice(1).join("_")] = db[i];
  }
}

for (var k in prefixedDb) {
  if (prefixedDb.hasOwnProperty(k)) {
    var db = prefixedDb[k];
    var dbIndexed = {};

    for (var i in db) {
      if (db.hasOwnProperty(i)) {
        var vals = db[i].split(',');

        vals.forEach(function(val, j) {
          if (dbIndexed[j] === undefined) {
            dbIndexed[j] = {};
          }

          dbIndexed[j][i] = val;
        });
      }
    }

    result += "<table><tbody>";

    for (var i in dbIndexed) {
      if (dbIndexed.hasOwnProperty(i)) {
        result += "<tr>";

        var indexVals = dbIndexed[i];
        for (var j in indexVals) {
          if (indexVals.hasOwnProperty(j)) {
            result += "<td>" + j + " " + i + " - " + indexVals[j] + "</td>";
          }
        }

        result += "</tr>";
      }
    }

    result += "</tbody></table>";
  }
}

document.write(result);

请注意,此代码可能不是此任务的最佳代码。

答案 1 :(得分:1)

创建一个循环,递增一个计数器,它将确定是否应该输出一个键的分割值。

如果在计数器的索引处找不到更多值,则停止循环。

var db = {
    "id": "8",
    "user_id": "24",
    "batchno": "367727",
    "ht_number": "jibhbu",
    "ht_taste": "uvyutvc",
    "pp_flavour": "ytv,yurtcrc,urt",
    "pp_fruit_batch": "cuyt,cytc,yt",
    "sl_flavour": "ouihyuigytvytc",
    "sl_appearance": "rtctr"
  },
  s = '';

['pp_', 'ht_', 'sl_'].forEach(function(type) {
  var i,
      found = true;
  
  s += '<table>';
  
  for(i = 0 ; found ; i++) {
    s += '<tr>';
    found = false;
    Object.keys(db).forEach(function(key) {
      var js = db[key].split(',');
    
      if(js[i] && key.startsWith(type)) {
        found = true;
        s += '<td>' + key + ' ' + i + ' : ' + js[i] + '</td>';
      }
    });
    s += '</tr>';
  }
  s += '</table>';
});

document.write(s);
td {
  border-bottom: 1px solid #bbb;
  border-right: 1px solid #ddd;
  padding: 0.5em;
}

table {
  border: 1px solid black;
  margin-bottom: 1em;
  border-spacing: 0;
}

答案 2 :(得分:1)

您可以从对象中取出所需的值,拆分它们并使用最大长度来迭代表的行。然后通过迭代值来组装表。

var db = { pp_flavour: "ytv,yurtcrc,urt", pp_fruit_batch: "cuyt,cytc,yt,42" },
    values = Object.keys(db).filter(k => k.startsWith('pp_')).map(k => (db[k] || '').split(',')),
    length = values.reduce((r, a) => Math.max(r, a.length), 0),
    table = document.createElement('table'),
    tr,
    i;

for (i = 0; i < length; i++) {
    tr = document.createElement('tr');
    table.appendChild(tr);
    values.forEach(function (a) {
        var td = document.createElement('td');
        td.appendChild(document.createTextNode(i in a ? a[i] : ''));
        tr.appendChild(td);
    });
}

document.body.appendChild(table);

答案 3 :(得分:1)

您可以尝试将表格的每个值添加到 2-D数组,然后从此2-D数组中形成表格

尝试以下解决方案

注意:这也适用于不同数量的行和列。

var db = {
    "id": "8",
    "user_id": "24",
    "batchno": "367727",
    "ht_number": "jibhbu",
    "ht_taste": "uvyutvc",
    "pp_flavour": "ytv,yurtcrc,urt",
    "pp_fruit_batch": "cuyt,cytc,yt",
    "sl_flavour": "ouihyuigytvytc",
    "sl_appearance": "rtctr"
  };
function createTable(myKey){
var  rows = [];
for (var dbKey in db) {
  if (db.hasOwnProperty(dbKey)) {
    if (dbKey.startsWith(myKey)) {
      var values = db[dbKey].split(',');
      for (var val in values) {
        if (!rows[val])
          rows[val] = [];
        rows[val].push('<td>' + dbKey + ' ' + val + ' : ' + values[val] + '</td>');
      }
    }
  }
}

var myTable = '<table><tbody>';
for (var i = 0; i < rows.length; i++) {
  myTable += "<tr>" + rows[i].join("") + "</tr>";
}
myTable += '</tbody></table>';
return myTable;
}
var ht_table = createTable("ht_");
document.getElementById("myTable").innerHTML +="<br/>"+ ht_table;

var pp_table = createTable("pp_");
document.getElementById("myTable").innerHTML +="<br/>"+ pp_table;

var sl_table = createTable("sl_");
document.getElementById("myTable").innerHTML += "<br/>"+ sl_table;
table, td {
  border-style: solid;
}
<p id="myTable">

</p>