首页 > 解决方案 > 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中的任何一个匹配的所有对象,这些对象具有相同的和或仅或仅。comparescopesectorscopesector

我已经尝试过.filter()功能,但没有让它工作:

const filteredCards = objArray.filter(card =>{
    return card.scope   === compare.scope
        && card.sector  === compare.sector;
});

标签: javascriptloopsecmascript-6

解决方案


请尝试此代码。

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)


推荐阅读