我正在比较匹配项目的两个数组,但我需要使它们不区分大小写。
这是代码:这个代码归功于@PatrickRoberts here
const words = ['word1', 'word2', 'word3']
const texts = [
{name: 'blah', description: 'word4'},
{name: 'blah2', description: 'word1'},
{name: 'blah3', description: 'word5'}
]
console.log(
texts.some(
({ description }) => words.includes(description)
)
)
我能够通过做words.includes(description.toLowerCase())
得到第二部分小写,但我不知道如何处理第一部分:texts.some(({ description })
我应该提到我已经尝试添加toLowerCase()到{description}像这样:{ description.toLowerCase() }
但这不工作
任何帮助是极大的赞赏
切换到函数some
或函数find
或函数findIndex
。
const words = ['Word1', 'word2', 'word3']
const texts = [{ name: 'blah', description: 'word4' }, { name: 'blah2', description: 'word1' }, { name: 'blah3', description: 'word5' }];
console.log(texts.some(({description}) => words.some((w) => w.toLowerCase() === description.toLowerCase())));
不,在解构过程中不可能改变它 - this answer解释了原因。
使用some
而不是includes
检查要容易得多:
const words = ['word1', 'word2', 'word3']
const texts = [{
name: 'blah',
description: 'word4'
},
{
name: 'blah2',
description: 'word1'
},
{
name: 'blah3',
description: 'word5'
}
]
console.log(
texts.some(
({
description
}) => words.some(word => word.toLowerCase == description.toLowerCase())
)
)
JSON.stringify
将对象转换为字符串.toLowerCase
应用于获取的字符串,以便所有内容(包括所有值)都变为小写JSON.parse
转换回对象或数组Array.some
和Array.includes
const words = ['WORD1', 'WORD2', 'WORD3'];
const texts = [
{name: 'blah', description: 'word4'},
{name: 'blah2', description: 'word1'},
{name: 'blah3', description: 'word5'}
];
const lower = x => JSON.parse(JSON.stringify(x).toLowerCase());
const [lowerWords, lowerTexts] = [words, texts].map(lower);
console.log(
lowerTexts.some(
({ description }) => lowerWords.includes(description)
)
)