将Cheerio对象映射到“本地”对象数组中

时间:2018-11-04 01:21:39

标签: 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(...)插入该数组。

0 个答案:

没有答案
相关问题