如何解决如何找到特殊字符,例如“!”要么 '?'在JavaScript中的对象数组中?
我想用'!'查找用户名。和'?'在对象数组中并将其存储在新数组中。 对象数组如下。
const array = [
{
username: "john!",team: "red",score: 5,items: ["ball","book","pen"]
},{
username: "becky",team: "blue",score: 10,items: ["tape","backpack",{
username: "susy?",score: 55,"eraser",{
username: "tyson",team: "green",score: 1,items: ["book",];
我尝试了test()
循环的forEach
方法,但无法获得首选输出。有什么建议?我可以使用map()
而不是forEach
来遍历对象吗?
解决方法
解决方案
这是一个简单的单行解决方案
const arr = [
{
username: "john!",team: "red",score: 5,items: ["ball","book","pen"]
},{
username: "becky",team: "blue",score: 10,items: ["tape","backpack",{
username: "susy?",score: 55,"eraser",{
username: "tyson",team: "green",score: 1,items: ["book",]
let newArr = []
arr.forEach(({username}) => username.match(/[?|!]/g) ? newArr.push(username) : null)
console.log(newArr)
工作原理
首先,我们使用以下命令遍历数组中的所有元素:
arr.forEach(({username}) => ...)
然后我们检查username
是否包含'!'要么 '?'使用正则表达式(Regex):
username.match(/[?|!]/g)
如果确实包含“?”要么 '!'然后将您的用户名推送到新数组:
newArr.push(username)
如果用户名不匹配,请返回null
const array = [
{
username: "john!",];
const usernames = array
.filter(({ username }) => /\?|!/.test(username))
.map(({ username }) => username);
console.log(usernames);
,
特定于您的用例,这就是您如何获取包含这些字符的所有用户名的方式。
Array.filter
创建了一个新数组,因此您不必突变原始数组即可获取所需的值。
array.filter(obj => obj.username.includes("!") || obj.username.includes("?"))
,
我认为这应该可以完成工作。
const names = array.reduce((acc,item) => {
if (/[!?]$/.test(item.username)) {
acc.push(item.username);
}
return acc;
},[]);
,
使用Array.prototype.filter()筛选出用户名包含!的对象。要么 ?或其他您要检查到的新字符。
const array = [
{
username: 'john!',team: 'red',items: ['ball','book','pen'],},{
username: 'becky',team: 'blue',items: ['tape','backpack',{
username: 'susy?','eraser',{
username: 'tyson',team: 'green',items: ['book',];
const filteredArray = array.filter(object => {
//You need to add your characters in the below condition to check for them I have //added for ! & ? for now
return object.username.includes('!') || object.username.includes('?');
});
console.log(filteredArray);
//To get just the usernames
filteredArray.forEach(object => console.log(object.username));
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。