javascript

时间:2019-03-01 23:13:06

标签: javascript arrays array-filter

我正在比较匹配项的两个数组,但需要使它们不区分大小写。

下面是代码:此代码归@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() },但这不起作用

非常感谢您的帮助

3 个答案:

答案 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)

  1. 使用JSON.stringify将您的对象转换为字符串
  2. .toLowerCase应用于获得的字符串,以便所有内容(包括所有值)都变为小写
  3. 使用JSON.parse
  4. 转换回对象或数组
  5. 将其余的匹配逻辑应用于Array.someArray.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())
  )
)