使用过滤器过滤对象

时间:2018-07-06 07:57:45

标签: javascript arrays filter ecmascript-6

我有如下所示的对象数组:

pages= [
   {
      "id":1,
      "name":"name1",
      "languages":[
         {
            "id":1,
            "lang":"en"
         },
         {
            "id":2,
            "lang":"de"
         }
      ]
   },
   {
      "id":2,
      "name":"name2",
      "languages":[
         {
            "id":1,
            "lang":"en"
         },
         {
            "id":2,
            "lang":"de"
         }
      ]
   },
   {
      "id":3,
      "name":"name3",
      "languages":[
         {
            "id":1,
            "lang":"en"
         }
      ]
   }
]

语言数组(将通过单击复选框进行设置)如下:

selectedLanguages=['en'];

现在,我想根据selectedLanguages值过滤主数组。我尝试使用以下代码:

pages.filter(page => {
    var present = false;
    page.languages.map(l => {
        if(selectedLanguages.includes(l.lang)) {
            present = true;
        }
    });
    if(present) {
        return page;
    }
})

所需的输出:如果为selectedLanguages = ['en'],则来自pages的所有项目;如果为de,则为前2个元素。

它可以工作,但是我很好奇是否可以做得更好?

任何建议都会有所帮助:)谢谢。

3 个答案:

答案 0 :(得分:1)

为此,您可以使用Array#FilterArray#findArray#includes的组合:

let pages= [
   {
      "id":1,
      "name":"name1",
      "languages":[
         {
            "id":1,
            "lang":"en"
         },
         {
            "id":2,
            "lang":"de"
         }
      ]
   },
   {
      "id":2,
      "name":"name2",
      "languages":[
         {
            "id":1,
            "lang":"en"
         },
         {
            "id":2,
            "lang":"fr"
         }
      ]
   }
]

let selectedLanguages=['fr'];

let result = pages.filter(e => e.languages.find(l => selectedLanguages.includes(l.lang)));
console.log(result);

答案 1 :(得分:1)

与其尝试用.map创建中间数组,不如简单地检查some中的languages是否包含与{{1 }}:

lang

答案 2 :(得分:0)

您可以将filter()indexOf()一起使用来检查selectedLanguages数组:

var pages= [
   {
      "id":1,
      "name":"name1",
      "languages":[
         {
            "id":1,
            "lang":"en"
         },
         {
            "id":2,
            "lang":"de"
         }
      ]
   },
   {
      "id":2,
      "name":"name2",
      "languages":[
         {
            "id":1,
            "lang":"en"
         },
         {
            "id":2,
            "lang":"de"
         }
      ]
   },
    {
      "id":3,
      "name":"name3",
      "languages":[
         {
            "id":5,
            "lang":"us"
         },
         {
            "id":6,
            "lang":"de"
         }
      ]
   }
];

var selectedLanguages=['en'];

var res = pages.filter((page) => {
   var languageFound = page.languages.find(language => selectedLanguages.indexOf(language.lang) !== -1);
   if(languageFound){
     return page;
   }
});

console.log(res);