无法过滤类似数组的对象

时间:2019-07-25 07:49:39

标签: javascript lodash domparser

我想在HTML中检索[image]标签,因此我使用 DOMParser 将字符串解析为一个对象。但是,当Lodash使用._filter时,我无法获得图像阵列。

奇怪的是,使用._find时我可以得到结果。

我已经在线搜索了解决方案,但找不到与我的案子相关的内容,请赐教。谢谢。

const content = '<!DOCTYPE html><html><head><meta name="keywords" content="seo, search engine optimisation, search engine optimization, search engine ranking"><meta name="description" content="A pages description, usually one or two sentences."/><title>Page title 123</title><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css"></head><body><h1>Hello there</h1><p><img src="https://fallbacks.carbonads.com/nosvn/fallbacks/731050e6bd3fc6979e1cb1a972294dae.png" class="fr-fic fr-dii"></p><a href="domain.com">This is domain</a><a href="domain.com2">This is domain2</a></body></html>';

let parser = new DOMParser(),
    parsedHtml = parser.parseFromString(content, 'text/html'),
    tagsInHtml = parsedHtml.all;

// ## Filter the data
let hrefArray   = _.filter(tagsInHtml, { "tagName": "A" }), // ??? Empty [] array
    hrefArray2  = _.find(tagsInHtml,   { "tagName": "A" }), // This working;

附带JSFiddle

1 个答案:

答案 0 :(得分:3)

您需要先将标签集合转换为Array

const content = '<!DOCTYPE html><html><head><meta name="keywords" content="seo, search engine optimisation, search engine optimization, search engine ranking"><meta name="description" content="A pages description, usually one or two sentences."/><title>Page title 123</title><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css"></head><body><h1>Hello there</h1><p><img src="https://fallbacks.carbonads.com/nosvn/fallbacks/731050e6bd3fc6979e1cb1a972294dae.png" class="fr-fic fr-dii"></p><a href="domain.com">This is domain</a><a href="domain.com2">This is domain2</a></body></html>';

let parser = new DOMParser(),
    parsedHtml = parser.parseFromString(content, 'text/html'),
    tagsInHtml = parsedHtml.all,
    tags = Array.from(tagsInHtml);
    
// Filter the data
let hrefArray = _.filter(tags, { 'tagName': 'A' }),
    hrefArray2 = _.find(tags, { 'tagName': 'A' });
    
console.dir(hrefArray);
console.dir(hrefArray2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>