英文:
get variable outside for loop
问题
我创建的代码如下:
for (var b = 0; b < parseDataArr.length; b++) {
for (var c = 0; c < parseDataArr[b].data_item.length; c++) {
for (var d = 0; d < parseDataArr[b].data_item[c].data_receipt.length; d++) {
var kartonReceipt = parseDataArr[b].data_item[c].data_receipt[d].cartonIRBar
}
}
}
log.debug('carton for', cartonIRBar) // not all result for loop only last data has record
如何在不将 debug()
语句移到循环内部的情况下获取 cartonIRBar
的所有结果数据?
英文:
I create code like this:
for (var b = 0; b < parseDataArr.length; b++) {
for (var c = 0; c < parseDataArr[b].data_item.length; c++) {
for (var d = 0; d < parseDataArr[b].data_item[c].data_receipt.length; d++) {
var kartonReceipt = parseDataArr[b].data_item[c].data_receipt[d].cartonIRBar
}
}
}
log.debug('carton for',cartonIRBar) // not all result for loop only last data has record
How do I get all the result data from cartonIRBAr
without moving the debug()
statement inside the loop?
答案1
得分: 1
要获取嵌套数组中所有`cartonIRBar`值的信息,您需要将这些值累积到一个数据结构中,如一个数组。
您可以使用嵌套的[`flatMap()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap)方法:
```javascript
const kartonReceipts = parseDataArr.flatMap(
({data_item}) => data_item.flatMap(
({data_receipt}) => data_receipt.flatMap(
({cartonIRBar}) => cartonIRBar
)
)
);
完整代码片段:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const parseDataArr = [{
data_item: [{
data_receipt: [{
cartonIRBar: 'value1'
}]
}]
}, {
data_item: [{
data_receipt: [{
cartonIRBar: 'value2'
}, {
cartonIRBar: 'value3'
}]
}]
}];
const kartonReceipts = parseDataArr.flatMap(
({data_item}) => data_item.flatMap(
({data_receipt}) => data_receipt.flatMap(
({cartonIRBar}) => cartonIRBar
)
)
);
console.log(kartonReceipts);
<!-- end snippet -->
英文:
To get information about all the cartonIRBar
values in that deeply nested array, you need to accumulate those values into a data structure, like an array.
You could use a nested flatMap()
approach:
const kartonReceipts = parseDataArr.flatMap(
({data_item}) => data_item.flatMap(
({data_receipt}) => data_receipt.flatMap(
({cartonIRBar}) => cartonIRBar
)
)
);
Complete snippet:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const parseDataArr = [{
data_item: [{
data_receipt: [{
cartonIRBar: 'value1'
}]
}]
}, {
data_item: [{
data_receipt: [{
cartonIRBar: 'value2'
}, {
cartonIRBar: 'value3'
}]
}]
}];
const kartonReceipts = parseDataArr.flatMap(
({data_item}) => data_item.flatMap(
({data_receipt}) => data_receipt.flatMap(
({cartonIRBar}) => cartonIRBar
)
)
);
console.log(kartonReceipts);
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论