NodeJS 如何使用子字符串搜索对关键字和值对过滤javascript数组

fkaflof6  于 2022-11-22  发布在  Node.js
关注(0)|答案(5)|浏览(149)

在下面的数组中,我要筛选出与关键字StartTime的子字符串“11/2022”匹配的记录

[
  {
    StartTime: '17/10/2022 14:45',
    Duration: '000:00:44:32',
  },
  {
    StartTime: '17/11/2022 14:45',
    Duration: '000:00:44:30',
 
  },
  {
    StartTime: '18/11/2022 14:45',
    Duration: '000:00:44:30',
 
  },  
   {
    StartTime: '17/12/2022 14:45',
    Duration: '000:00:44:30',
 
  }
]

预期输出:

[
   {
    StartTime: '17/11/2022 14:45',
    Duration: '000:00:44:30',
 
  },
   {
    StartTime: '18/11/2022 14:45',
    Duration: '000:00:44:30',
 
  }
   
]
js81xvg6

js81xvg61#

可以像这样使用includes函数

[
    { StartTime: "17/10/2022 14:45", Duration: "000:00:44:32" },
    { StartTime: "17/11/2022 14:45", Duration: "000:00:44:30" },
    { StartTime: "18/11/2022 14:45", Duration: "000:00:44:30" },
    { StartTime: "17/12/2022 14:45", Duration: "000:00:44:30" },
  ].filter((item) => item.StartTime.includes("11/2022"));
yshpjwxd

yshpjwxd2#

你可以使用filter()来循环遍历对象数组,并为每个对象项检查StartTime()是否包括任何搜索关键字的子字符串。

const array = [{
    StartTime: '17/10/2022 14:45',
    Duration: '000:00:44:32',
  }, {
    StartTime: '17/11/2022 14:45',
    Duration: '000:00:44:30',

  }, {
    StartTime: '18/11/2022 14:45',
    Duration: '000:00:44:30',

  },
  {
    StartTime: '17/12/2022 14:45',
    Duration: '000:00:44:30',

  }
];

const searchKey = '11/2022';
const filteredArray = array.filter(item => item.StartTime.includes(searchKey));

console.log(filteredArray);

希望能有所帮助!

nlejzf6q

nlejzf6q3#

只要使用Array.filter()就可以做到

let data = [
  {
    StartTime: '17/10/2022 14:45',
    Duration: '000:00:44:32',
  },
  {
    StartTime: '17/11/2022 14:45',
    Duration: '000:00:44:30',
 
  },
  {
    StartTime: '18/11/2022 14:45',
    Duration: '000:00:44:30',
 
  },  
   {
    StartTime: '17/12/2022 14:45',
    Duration: '000:00:44:30',
 
  }
]

let result = data.filter(d => d.StartTime.includes('/11/2022'))
console.log(result)
rsaldnfx

rsaldnfx4#

您可以使用.filter().includes()

const input = [
    { StartTime: '17/10/2022 14:45', Duration: '000:00:44:32', },
    { StartTime: '17/11/2022 14:45', Duration: '000:00:44:30', },
    { StartTime: '18/11/2022 14:45', Duration: '000:00:44:30', },
    { StartTime: '17/12/2022 14:45', Duration: '000:00:44:30', }
];

const result = input.filter(element => {
    return element.StartTime.includes("11/2022");
});

console.log(result);
kcugc4gi

kcugc4gi5#

你可以使用filter()和正则表达式来检查你的字符串中是否有子字符串,正则表达式也提供了很多有用的选项,所以它们可能会在将来对你有所帮助

const arr = [
    { StartTime: '17/10/2022 14:45', Duration: '000:00:44:32', }, 
    { StartTime: '17/11/2022 14:45', Duration: '000:00:44:30', }, 
    { StartTime: '18/11/2022 14:45', Duration: '000:00:44:30', },
    { StartTime: '17/12/2022 14:45', Duration: '000:00:44:30',}
]

const newArr = arr.filter(elem => elem.StartTime.match("11/2022"))

相关问题