【问题标题】:I have array with objects, I need to fetch all the objects that matches the value of userId starts with 'US' [duplicate]我有对象数组,我需要获取与 userId 的值匹配的所有对象,以“US”开头 [重复]
【发布时间】:2022-01-02 08:27:33
【问题描述】:

下面是包含对象的数组:

myArray:[    
    {"name":"Ram", "email":"ram@gmail.com", "userId":"HB000006"},    
    {"name":"Shyam", "email":"shyam23@gmail.com", "userId":"US000026"},  
    {"name":"John", "email":"john@gmail.com", "userId":"HB000011"},    
    {"name":"Bob", "email":"bob32@gmail.com", "userId":"US000106"}   
    ]}  

我试过了,但没有得到输出:

    item= myArray.filter(element => element.includes("US"));

我是 Angular 的新手。

【问题讨论】:

  • 您的代码假定myArray 是字符串数组,而不是具有字符串属性的对象数组。

标签: javascript angularjs


【解决方案1】:
let filteredArray = myArray.filter(function (item){
        return item.userId.substring(0,2).includes('US')
    })
    Console.log(filteredArray)

//输出

[{名称:'Shyam',电子邮件:'shyam23@gmail.com',用户ID:'US000026'}, { 姓名:“鲍勃”,电子邮件:“bob32@gmail.com”,用户 ID:“US000106”} ]

【讨论】:

  • 请不要将答案发布到如此讨厌的重复...
【解决方案2】:

正如@halfer 所指出的 - 您需要过滤您感兴趣的属性 - 在这种情况下 - 'userId' - 您可以通过简单地将属性添加到您已经尝试过的代码中来做到这一点,它会记录取出指定的项目 - 或者 - 您可以创建一个实用函数,将数组、属性和目标字符串作为参数,这将允许您搜索/过滤其他数组以及任何属性和目标字符串。

这两个选项如下所示,并且都注销了相同的结果。

const myArray = [    
    {"name":"Ram", "email":"ram@gmail.com", "userId":"HB000006"},    
    {"name":"Shyam", "email":"shyam23@gmail.com", "userId":"US000026"},  
    {"name":"John", "email":"john@gmail.com", "userId":"HB000011"},    
    {"name":"Bob", "email":"bob32@gmail.com", "userId":"US000106"}   
    ]
    
// option 1 - direct filtering
const matchingItems = myArray.filter(element => element.userId.includes("US"));
console.log(matchingItems);

// gives - [ { name: 'Shyam', email: 'shyam23@gmail.com', userId: 'US000026' }, { name: 'Bob', email: 'bob32@gmail.com', userId: 'US000106' } ]


//option 2 - create a function that takes arguments and returns the matches
const matches = (arr, prop, str) => {
 return  arr.filter(element => element[prop].includes(str));
}
console.log(matches(myArray, 'userId', 'US'));

// gives - [ { name: 'Shyam', email: 'shyam23@gmail.com', userId: 'US000026' }, { name: 'Bob', email: 'bob32@gmail.com', userId: 'US000106' } ]

【讨论】:

  • 请不要发布如此明显重复的答案...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-11
  • 1970-01-01
  • 1970-01-01
  • 2016-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多