循环和检查两个数组总是只返回一个元素

时间:2017-12-01 12:54:19

标签: javascript arrays

我有两个数组,一个是字符串['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 个答案:

答案 0 :(得分:1)

或者您可以使用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