typescript 我需要过滤对象数组,过滤发生在条件startwith和字符串包含

pepwfjgg  于 2023-06-07  发布在  TypeScript
关注(0)|答案(3)|浏览(144)

这是我的对象数组,我需要用name过滤这个
案例一:如果我从案例开始搜索“tali”过滤器结果,同时用户输入“tali Co OP”获得结果“塔利帕兰巴Co Op Hospital”
情况二:如果我搜索“ath”,得到的结果是“Athikkal Saw Mill,Kallai”和“Marhaba Ice Plant Atholi”,因为“Marhaba Ice Plant Atholi”中包含Ath

test = [{ id: 1, name: 'Taliparamba Co Op Hospital' },
    { id: 1, name: 'Athikkal Saw Mill,Kallai' },
    { id: 1, name: 'Marhaba Ice Plant Atholi' },]
polhcujo

polhcujo1#

const test = [
      { id: 1, name: 'Taliparamba Co Op Hospital' },
      { id: 1, name: 'Athikkal Saw Mill,Kallai' },
      { id: 1, name: 'Marhaba Ice Plant Atholi' },
    ];

    function search(arr, str) {
      const regexp = new RegExp('\\b' + str.split(' ').join('.*?\\b'), 'i');
      return arr.filter((item) => regexp.test(item.name));
    }

    console.log(search(test, 'tali'));
    console.log(search(test, 'tali Co OP'));
    console.log(search(test, 'ath'));
e37o9pze

e37o9pze2#

const test = [{ id: 1, name: 'Taliparamba Co Op Hospital' },
    { id: 1, name: 'Athikkal Saw Mill,Kallai' },
    { id: 1, name: 'Marhaba Ice Plant Atholi' },]
    
const myString = "ath"; // your search string goes here
const result = test.filter(eachObject => {
    return eachObject.name.toLowerCase().search(myString) !== -1
})

console.log("result is", result)
63lcw9qa

63lcw9qa3#

我认为下面的代码行应该为你做的工作

const test = [
    { id: 1, name: 'Taliparamba Co Op Hospital' },
    { id: 2, name: 'Athikkal Saw Mill,Kallai' },
    { id: 3, name: 'Marhaba Ice Plant Atholi' },
];

const searchedStr = 'Ath'
const results = test.filter(obj => 
    obj.name.includes(searchedStr) || 
    obj.name.includes(searchedStr.toLowerCase())
);

console.log(results)

请告诉我们进展如何

相关问题