[英]How do I convert my objects to an array in node.js?
When I execute the code below in node, the command prompt complains that it needs an array of objects in order to use objects-to-csv.当我在节点中执行下面的代码时,命令提示符抱怨它需要一个对象数组才能使用 objects-to-csv。
const ObjectsToCsv = require("objects-to-csv");
async function scrapeDescription(url, page) {
//more code ...
return {url, cats, main_img, name, descript, price};
}
async function saveDataToCsv(data) {
const csv = new ObjectsToCsv(data);
await csv.toDisk("spreadsheets/output.csv");
}
browser = await puppeteer.launch({ headless: false});
const descriptionPage = await browser.newPage();
for (var i=0; i< 2; i++){
result = await scrapeDescription(scrapeResults[i], descriptionPage);
console.log(result);
}
await saveDataToCsv(result);
When I don't use the saveDataToCsv(data) function, I get the following results:当我不使用 saveDataToCsv(data) function 时,我得到以下结果:
{
url: 'https://www.example.com/product_info.php?products_id=479684',
cats: 'JEWELRY < ANKLET < FASHION < ',
main_img: 'images/20200312/AK001501.jpg',
name: 'Faceted Bead Pearl Link Anklet',
descript: ' Style No : 479684 Color : Multi Theme : Pearl Size : 0.2"H, 9" + 3" L One Side Only Lead and Nickel Compliant Faceted Bead Pearl Link Anklet',
price: '$2.25 / pc'
}
{
url: 'https://www.example.com/product_info.php?products_id=479682',
cats: 'JEWELRY < ANKLET < FASHION < ',
main_img: 'images/20200312/AK0001.jpg',
name: 'Freshwater Pearl Disc Beaded Anklet',
descript: ' Style No : 479682 Color : Neutral Theme : Pearl Size : 0.25"H, 9" + 3" L One Side Only Lead and Nickel Compliant Freshwater Pearl Disc Beaded Anklet',
price: '$3.75 / pc$40.50 / dz'
}
So what I get is a couple of objects and I want to convert them to an array so that I can use objects-to-csv.所以我得到的是几个对象,我想将它们转换为一个数组,以便我可以使用 objects-to-csv。
I would change我会改变
for (var i=0; i< 2; i++){
result = await scrapeDescription(scrapeResults[i], descriptionPage);
console.log(result);
}
await saveDataToCsv(result);
to至
let arr = [];
for (var i=0; i< 2; i++){
result = await scrapeDescription(scrapeResults[i], descriptionPage);
arr.push(result);
console.log(result);
}
await saveDataToCsv(arr);
That way, you'll get all of your scraped objects in an array.这样,您将在一个数组中获取所有抓取的对象。 Let me know if that does it.让我知道是否这样做。
This question was solved at a different forum.这个问题在另一个论坛上得到了解决。 The trick was to use the spread operator inside of the for loop.诀窍是在 for 循环中使用扩展运算符。 resultsArray = [...resultsArray,result]; resultsArray = [...resultsArray,result];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.