首页 > 解决方案 > 将 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(...)

标签: typescriptcheerio

解决方案


推荐阅读