javascript - 从对象数组中返回匹配的对象
问题描述
我想根据searchString从给定数组中搜索匹配的值对象。例如,座位字符串将是“对象0”。
var objArray = [
{ id: 0, name: 'Object 0', otherProp: '321', secondVal:'stack' },
{ id: 1, name: 'O1', otherProp: 'Object 0', secondVal: 'Overflow' },
{ id: 2, name: 'Another Object', otherProp: '850', secondVal: 'Context' },
{ id: 3, name: 'Almost There', otherProp: '046', secondVal: 'Object 1' },
{ id: 4, name: 'Last Obj', otherProp: '78', secondVal: 'test' }
];
现在我只想搜索那些具有Object
价值的数组。意味着它应该返回我 0,1 & 3 对象
帮助将不胜感激
解决方案
您可以使用该array.filter
方法和在此过滤器方法中的所有属性上循环来做到这一点。
var objArray = [
{ id: 0, name: 'Object 0', otherProp: '321', secondVal:'stack' },
{ id: 1, name: 'O1', otherProp: 'Object 0', secondVal: 'Overflow' },
{ id: 2, name: 'Another Object', otherProp: '850', secondVal: 'Context' },
{ id: 3, name: 'Almost There', otherProp: '046', secondVal: 'Object 0' },
{ id: 4, name: 'Last Obj', otherProp: '78', secondVal: 'test' }
];
var filteredArray = objArray.filter((obj) => {
for (var key in obj) {
if (obj[key] === 'Object 0') {
return true;
}
}
return false;
});
推荐阅读
- groovy - 使用 Groovy 解析嵌套 Json 中的值
- javascript - 一起使用 HTML、PHP 和 Javascript
- python - scikit-learn 中的 one-vs-rest 是如何实现的?
- delphi - Python4Delphi,支持不同的Unix安装
- python - Python中的学习函数
- python - Python BeautifulSoup find_all - 如何在 html 中搜索字符串,忽略 html 中的所有空格和不间断空格?
- mysql - MySQL 查询以获取所有用户看到的帖子
- java - 测试 JpaRepository findById 为 UUID 返回 null
- docker - 将 Apache Cassandra 连接到 DataGrip
- vba - 尝试将文件复制到 VBA 中的 Sharepoint 365 站点