gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 02:56:41 25 4
gpt4 key购买 nike

我有两个数组,一个是字符串数组['security', 'hobbies'],另一个是对象数组[{name: 'randome' ,类别:'爱好'},{名称:'随机',类别:'随机'},{名称:'随机',类别:'随机'},{名称:'随机',类别:'安全'}] ,我试图循环两个数组并拼接所有那些与第一个数组上的类别不匹配的对象,但总是在循环中只获得一个元素。

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"

最佳答案

或者您可以使用过滤器

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

关于javascript - 循环并检查两个数组始终仅返回一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47593867/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com