ค้นหาเว็บไซต์

javascript - เราสามารถใช้ฟังก์ชัน .filter() กับกฎตามเงื่อนไขสำหรับคุณสมบัติที่ค้นหาได้หรือไม่?


สมมติว่าพวกเรามีฟังก์ชัน .filter ดังต่อไปนี้:

search(searchQuery: string) {
  let results = myArray.filter(item => 
    item.title.toLowerCase().includes(searchQuery) ||
    item.description.toLowerCase().includes(searchQuery)
  );

  return results;
}

สำหรับตัวอย่างนี้ เราสามารถพิจารณาว่า item ไม่มีคุณสมบัติ description เสมอไป แต่มีเพียงบางครั้ง ในกรณีนี้ ฟังก์ชันจะล้มเหลวพร้อมข้อผิดพลาด:

ข้อผิดพลาด TypeError: ไม่สามารถอ่านคุณสมบัติ 'toLowerCase' ของค่าที่ไม่ได้กำหนด

เราจะยังสามารถค้นหาในอาเรย์และรวมคุณสมบัติ description ในการค้นหาได้ก็ต่อเมื่อมันมีอยู่เท่านั้นได้อย่างไร? สิ่งนี้เป็นไปได้ภายในฟังก์ชัน .filter() หรือไม่?

คำตอบ #1

คุณสามารถใช้ค่าปริยายได้

โดยตรง

(item.description || '').toLowerCase().includes(searchQuery)

หรือใช้การแยกโครงสร้างพร้อมค่าตั้งต้น

results = myArray.filter(({ title = '', description = '' }) => 
    title.toLowerCase().includes(searchQuery) ||
    description.toLowerCase().includes(searchQuery)
);

คำตอบ #2

คุณสามารถทำอะไรบางอย่างแบบนี้ได้:

const myArray = [
    {
        title: 'Test 123',
    },
    {
        title: 'Test 123',
        description: 'test',
    },
    {
        title: 'What',
    },
    {
        title: 'Fix',
        description: '456123',
    },
];

const search = (text) => {
    let results = myArray.filter(item => {
        if (item.description) {
            return item.title.toLowerCase().includes(text) || item.description.toLowerCase().includes(text);
        }
    });
  
    return results;
}

const results = search('test');

console.log(results);