typescript - 将 Cheerio 对象映射到“本机”对象数组
问题描述
我通过cheerio加载的文档中有以下HTML(使用不同的数据重复了几次) :
<li class="wprm-recipe-ingredient">
<span class="wprm-recipe-ingredient-amount">1</span>
<span class="wprm-recipe-ingredient-unit">pound</span>
<span class="wprm-recipe-ingredient-name">extra lean ground beef</span>
</li>
这是我编写的表达我意图的代码:
const $ingredients = $("li[class='wprm-recipe-ingredient']");
const ingredients = $ingredients.map((_idx, $e) => {
const $elem = $($e);
const amount = $elem.children('[class$="-amount"]').text();
const unit = $elem.children('[class$="-unit"]').text();
const name = $elem.children('[class$="-name"]').text();
return { amount, unit, name };
}); // => [{amount, unit, name}, { ... }]
但该评论说明了我想要的,而不是我实际得到的。
实际类型是const ingredients: Cheerio
,它不是具有我尝试创建的形状的匿名对象数组。
如何映射$ingredients
到以下形状?
[{ amount: '1', unit: 'pound', name: 'extra lean ground beef' }]
请注意,据我所知,Cheerio 的回报.get()
不是我想要的。string[]
CheerioElement[]
编辑:
我应该对此进行一些扩展。
我目前正在做的是预先创建一个数组,然后push
在闭包结束时添加到该数组上$ingredients.forEach(...)
。
解决方案
推荐阅读
- javascript - 打字稿:胖箭头和这个范围关系
- shell - 缺少目标文件操作数?
- microsoft-graph-api - Microsoft Graph 的 Excel OData 提要 - 身份验证问题
- scala - 斯卡拉:嵌套getOrElse
- reactjs - 如何使用 React 处理两个不同的 API?
- ios - 如何让 2 个不相关的 Swift 对象知道如何执行相同的功能集
- android - 无法使用 SQLite 将数据插入数据库,出现空指针异常
- arrays - 如何将小切片复制到较大切片的末尾
- reactjs - 如何让 Flow 理解组件将通过 cloneElement 接收所需的道具?
- python - openpyxl 正在从其他工作表中删除数据,而不是保留外部数据引用