Javascript通过包含搜索词的标签子数组来过滤或减少每个JSON对象 [英] Javascript Filter or Reduce each JSON object by child array of tags which contains search word

查看:65
本文介绍了Javascript通过包含搜索词的标签子数组来过滤或减少每个JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要有关子对象array属性的给定Javascript Array下面的过滤的帮助.

I need help regarding filtering below given Javascript Array of Objects by it's sub-child array property.

我有一个react应用,当用户在搜索框中键入字符串时,我想在其中过滤文章,但是我的问题与仅通过对象的子数组值过滤对象有关.

I have one react app in which I want to filter articles when user types string in search box, but my question is related to just filtering objectby it's child array value.

this.state = {
 articles: [
    {title: 'title 1', tags :["JavaScript", "ES6"], category: "JavaScript"},
    {title: 'title 2', tags :["React", "TypeScript"], category: "React"},
    {title: 'title 3', tags :["JavaScript", "Inheritance", "Prototype"], category: "JavaScript"}
 ]
};

//需要输出

// If user start typing in searchbox like "jav" then it should filter only those items which tags name matching with "jav". Tags is an Array

 [
    {title: 'title 1', tags :["JavaScript", "ES6"], category: "JavaScript"},
    {title: 'title 3', tags :["JavaScript", "Inheritance", "Prototype"], category: "JavaScript"}
 ]

我尝试了以下给定的代码,但未给出正确的结果:

I had tried below given code but not giving proper result:

this.state.articles.reduce((newArticles: any, article: any) => {
            // let test1 = [];
            if (article.tags) {
                article.tags.map(tag => {
                    if (tag && tag.toLowerCase().indexOf(event.target.value) === -1) {
                        newArticles.push(article);
                        // return article;
                    }
                });
            } else {
                // newArticles.push(article);
            }

            console.log('test1 =', newArticles);
            return newArticles;
        }, []);

如果我的问题不清楚或需要更多信息,请告诉我.

Please let me know if my question is not clear or need more information on it.

谢谢,吉涅什·拉瓦尔(Jignesh Raval)

Thanks, Jignesh Raval

推荐答案

您可以使用内部的 filter 方法执行此操作,以检查 some 标记是否包含您要搜索的字符串的一部分.

You can do this with filter method in inside check if some tag includes part of string that you want to search for.

let articles = [{title: 'title 1', tags :["JavaScript", "ES6"], category: "JavaScript"},{title: 'title 2', tags :["React", "TypeScript"], category: "React"},{title: 'title 3', tags :["JavaScript", "Inheritance", "Prototype"], category: "JavaScript"}]
 
let search = 'java';
let result = articles.filter(({tags}) => {
  return tags.some(e => e.toLowerCase().includes(search.toLowerCase()))
})

console.log(result)

这篇关于Javascript通过包含搜索词的标签子数组来过滤或减少每个JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆