我正在比较匹配项的两个数组,但需要使它们不区分大小写。
下面是代码:此代码归@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() }
,但这不起作用
非常感谢您的帮助
答案 0 :(得分:2)
切换到功能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())));
答案 1 :(得分:0)
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)
)
)
答案 2 :(得分:0)
否,在销毁过程中无法更改它-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())
)
)