【问题标题】:Find words inside object value key that are stored in an array查找存储在数组中的对象值键内的单词
【发布时间】:2020-05-01 03:58:12
【问题描述】:

我收到一个有很多键的对象,其中两个是“title”和“body”,我还有一个包含一些关键字的数组。我需要匹配 object.body 中的这些数组关键字以以某种方式突出显示它们,一种选择可能是将这些匹配的单词包装在 <pre class="highlight"> Matched word inside Object.body </pre> 标记中。

我宁愿使用原始 JavaScript 来实现这一点。

我试过了:

function (data) {

        // parseKeys() returns an array with the words to find inside object.body
        var key_words = this.parseKeys();
 
// data is the object within I have to find inside key:body the array strings
        for (var i = 0; i < data.length; i++) {
          if (data[i].body.includes(key)){
            console.log("****");
          }
        }
      }

【问题讨论】:

  • 这是您在尝试中提出疑问和错误的论坛。您应该发布您的代码。没有人会为你写代码,毕竟你要试试!
  • 到目前为止您尝试过什么?你能给我们看一些代码吗?

标签: javascript object


【解决方案1】:

const keywords = ["doing", "only", "twice"];

const testObj = {
  title: "Whatever1",
  body: "Doing this only once or twice"
}

const checkBodyText = (obj) => {
  const bodyWords = obj.body.split(' ').map(el => el.toLowerCase());
  const matchingWords = bodyWords.filter(el => keywords.includes(el));
  const matchedWordsContainer = document.getElementsByClassName('highlight')[0];
  matchedWordsContainer.innerText = matchingWords.join(' ');
}

checkBodyText(testObj);
.highlight {
  color: red;
}
&lt;pre class="highlight"&gt;&lt;/pre&gt;

您可以创建一个变量来保存关键字。 我刚刚创建了一个虚拟对象,并将“object.body”中的每个单词与列表中的任何关键字进行比较,匹配的关键字只是简单地显示。 Ofc 这种方法还有一些其他的边缘场景,例如正文中的标点符号。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-22
    • 1970-01-01
    • 2018-04-05
    • 2021-10-25
    • 1970-01-01
    • 2022-12-02
    相关资源
    最近更新 更多