使用每个函数创建新的对象数组
Creating new Array of objects with an each function
我正在使用 node/puppeteer/cheerio
构建网络抓取工具
使用它我能够 console.log 正确的字符串。我很难理解这是否可能。
$('table[class="ad_tab"]')
.find("tbody > tr > td")
.each(function (index, element) {
if ((index + 1) % 8 == 0) {
console.log($(element).text());
console.log("Start New JSON");
} else {
console.log($(element).text());
}
我的输出是以下字符串
1
2
3
4
5
6
7
8
Start New JSON
9
10
11
12
13
14
15
16
Start New JSON
我的预期结果是:
[
{
"A": "1",
"B": "2",
"C": "3",
"D": "4",
"E": "5",
"F": "6",
"G": "7"
"H": "8"
},
{
"A": "9",
"B": "10",
"C": "11",
"D": "12",
"E": "13",
"F": "14",
"G": "15"
"H": "16"
}
]
您可以围绕此解决方案创建案例:
基本上从 each
替换为 reduce
.
let input = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17];
// input = $('table[class="ad_tab"]').find("tbody > tr > td")
let output = input.reduce((arr, value, i) => {
let remainder = i % 8;
if (!remainder) {
arr.push({})
};
let obj = arr[arr.length - 1];
let char = String.fromCharCode(97 + remainder);
obj[char] = value;
return arr;
}, []);
console.log(output)
我正在使用 node/puppeteer/cheerio
构建网络抓取工具使用它我能够 console.log 正确的字符串。我很难理解这是否可能。
$('table[class="ad_tab"]')
.find("tbody > tr > td")
.each(function (index, element) {
if ((index + 1) % 8 == 0) {
console.log($(element).text());
console.log("Start New JSON");
} else {
console.log($(element).text());
}
我的输出是以下字符串
1
2
3
4
5
6
7
8
Start New JSON
9
10
11
12
13
14
15
16
Start New JSON
我的预期结果是:
[
{
"A": "1",
"B": "2",
"C": "3",
"D": "4",
"E": "5",
"F": "6",
"G": "7"
"H": "8"
},
{
"A": "9",
"B": "10",
"C": "11",
"D": "12",
"E": "13",
"F": "14",
"G": "15"
"H": "16"
}
]
您可以围绕此解决方案创建案例:
基本上从 each
替换为 reduce
.
let input = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17];
// input = $('table[class="ad_tab"]').find("tbody > tr > td")
let output = input.reduce((arr, value, i) => {
let remainder = i % 8;
if (!remainder) {
arr.push({})
};
let obj = arr[arr.length - 1];
let char = String.fromCharCode(97 + remainder);
obj[char] = value;
return arr;
}, []);
console.log(output)