[英]Looping over array of arrays of objects
I have an array of arrays of objects that I want to loop over and print each element but for some reason, the loop is skipping some elements, and I understand why but I don't know what is the best way to fix it我有一个 arrays 的对象数组,我想循环并打印每个元素,但由于某种原因,循环跳过了一些元素,我明白为什么,但我不知道修复它的最佳方法是什么
Here is the code I used:这是我使用的代码:
const test = [
[
{
SESSION_ID: "200",
},
{
SESSION_ID: "296",
},
],
[
{
MICROFILM_REF_NUMBER: "9,52E+22",
},
{
MICROFILM_REF_NUMBER: "9,52E+22",
},
],
];
test.forEach((element, index) => {
console.log(element[index].SESSION_ID);
console.log(element[index].MICROFILM_REF_NUMBER);
});
The output I get is:我得到的 output 是:
200
undefined
undefined
9,52E+22
The desired output is:所需的 output 是:
200
296
9,52E+22
9,52E+22
You should probably use different data structure but for your question, this is one of answers您可能应该使用不同的数据结构,但对于您的问题,这是答案之一
test.forEach((array, index) => {
array.forEach((element, idx)=>{
if(element.SESSION_ID) console.log(element.SESSION_ID)
if(element.MICROFILM_REF_NUMBER) console.log(element.MICROFILM_REF_NUMBER)
})
});
I have an array of arrays of objects that I want to loop over and print each element but for some reason, the loop is skipping some elements, and I understand why but I don't know what is the best way to fix it我有一个 arrays 对象数组,我想循环并打印每个元素,但由于某种原因,循环跳过了一些元素,我明白为什么,但我不知道修复它的最佳方法是什么
Here is the code I used:这是我使用的代码:
const test = [
[
{
SESSION_ID: "200",
},
{
SESSION_ID: "296",
},
],
[
{
MICROFILM_REF_NUMBER: "9,52E+22",
},
{
MICROFILM_REF_NUMBER: "9,52E+22",
},
],
];
test.forEach((element, index) => {
console.log(element[index].SESSION_ID);
console.log(element[index].MICROFILM_REF_NUMBER);
});
The output I get is:我得到的 output 是:
200
undefined
undefined
9,52E+22
The desired output is:所需的 output 是:
200
296
9,52E+22
9,52E+22
Since you mentioned a table I believe you want something more along the lines of the following that maps your data to a rows
array that can then easily be iterated to insert rows and cells into a table element既然你提到了一个表,我相信你想要更多的东西沿着以下几行将你的数据映射到一个rows
数组,然后可以很容易地迭代以将行和单元格插入到表元素中
const col_props = ['SESSION_ID', 'MICROFILM_REF_NUMBER']; const rows = data[0].map((_, i) => { return data.map((arr, j) => arr[i][col_props[j]]); }); console.log('Rows:',JSON.stringify(rows)) // for headings in demo rows.unshift(col_props) const table = document.querySelector('#myTable'); rows.forEach(arr => { const row = table.insertRow() arr.forEach(v => row.insertCell().textContent = v) })
<table id="myTable" border="1"></table> <script> const data=[[{SESSION_ID:"200"},{SESSION_ID:"296"}],[{MICROFILM_REF_NUMBER:"9,52E+22"},{MICROFILM_REF_NUMBER:"9,52E+22"}]]; </script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.