javascript - Javascript | 使用对象循环遍历对象数组
问题描述
我有一个对象数组如下:
const objArray = [
{scope: "xx", sector: "yy", status: "pending", country: "USA"},
{scope: "zz", sector: "yy", status: "pending", country: "USA"}
{scope: "xx", sector: "yy", status: "pending", country: "USA"}
]
和一个对象如下:
const compare = {scope: "xx", sector: "yy"}
或者那个:
const compare = {scope: "xx"}
或者那个:
const compare = {scope: "yy"}
我想使用这三个对象之一遍历对象数组,并返回与这三个示例对象compare
中的任何一个匹配的所有对象,这些对象具有相同的和或仅或仅。compare
scope
sector
scope
sector
我已经尝试过.filter()
功能,但没有让它工作:
const filteredCards = objArray.filter(card =>{
return card.scope === compare.scope
&& card.sector === compare.sector;
});
解决方案
请尝试此代码。
const compare = {scope: "xx"};
const objArray = [
{scope: "xx", sector: "yy", status: "pending", country: "USA"},
{scope: "zz", sector: "yy", status: "pending", country: "USA"},
{scope: "xx", sector: "yy", status: "pending", country: "USA"}
];
var filter_result = objArray.filter(function(item) {
for (var key in compare) {
if (item[key] === undefined || item[key] != compare[key])
return false;
}
return true;
});
console.log(filter_result)
推荐阅读
- python - 由于额外的列值,尝试使用 pandas Python 读取 csv 时出错
- c# - 当角度 http.post 具有正确值时,为什么 obj 值在 asp Web API2 控制器中为空
- javascript - javascript es6类:在同一类的另一个方法中调用一个类的方法
- windows - 如何在不使用打印选项的情况下使用电子邮件中的快捷方式打印全屏
- javascript - 身份验证中间件不调用存根 - NodeJS,sinon
- c# - 我如何从 C# 将文件发布到 Web API?
- kubernetes - kubectl:无法连接到服务器:拨打 tcp 192.168.214.136:6443:连接:没有到主机的路由
- ios - 如何在不使用自动布局的情况下设置 UISegmentedControl 子类的高度?
- python - 从 Google Scholar 搜索结果中抓取和解析引文信息
- mysql - 使用 AND (OR) 基于多行值进行选择