代码之家  ›  专栏  ›  技术社区  ›  Miguel Frias

循环并检查两个数组始终只返回一个元素

  •  0
  • Miguel Frias  · 技术社区  · 8 年前

    Im有两个数组,一个是字符串数组 ['security', 'hobbies'] 另一个是对象的和数组 [{name: 'randome', category: 'hobbies'}, {name: 'randome', category: 'randome'}, {name: 'randome', category: 'randome'}, {name: 'randome', category: 'security'}] ,我尝试循环数组和 splice 所有与第一个数组上的类别不匹配但在循环中始终只获得一个元素的对象。

    for (let i = 0; i < searchparam.category.length; i++) {
            for (let j = 0; j < validapps.length; j++) {
              let match: boolean = false;
              if (validapps[j].category === searchparam.category[i]) {
                console.log(validapps[j])
                match = true;
                return;
              }
              if (!match) {
                validapps.splice(j, 1);
                j--;
              }
            }
     }
    

    循环后,我应该得到2个或更多的元素,但总是只有一个。 结果数据始终是一个元素。

    _id: "598c69259fe2ff5fd0432396"
    active: true
    app_language: Array [ "DE" ]
    application_code: "ASF"
    blacklist: Array []
    category: "utilities"
    comments: ""
    contacts: Array [ "598c40cf0f05ba5d0c5da01a", "598c66d59fe2ff5fd043238a", "59ce05683d7daf37702c1fc1", … ]
    id: "598c69259fe2ff5fd0432396"
    image: ""
    insertDate: "2017-08-10T14:09:41.189Z"
    name: "Alpha SSD Fresh"
    os: Array [ {…} ]
    updateDate: "2017-08-10T14:09:41.608Z"
    
    1 回复  |  直到 8 年前
        1
  •  1
  •   gurvinder372    8 年前

    或者你可以使用 filter

    var arr = [{name: 'randome', category: 'hobbies'}, {name: 'randome', category: 'randome'}, {name: 'randome', category: 'randome'}, {name: 'randome', category: 'security'}];
    var validItems = ['security', 'hobbies'];
    arr = arr.filter( s => validItems.indexOf( s.category ) != -1 ); //only those items will be passed through which have valid categories
    

    arr = arr.filter( s => validItems.includes( s.category ) ); //only those items will be passed through which have valid categories