gpt4 book ai didi

arrays - 使用另一个 JSON 数组 Node js 搜索 JSON 数组

转载 作者:搜寻专家 更新时间:2023-11-01 00:37:26 24 4
gpt4 key购买 nike

我正在尝试使用我使用的另一个 JSON 数组条件(过滤器)来过滤 JSON 数组。

这是我的代码:

function filterArray(object, criteria){
return object.filter(function(obj){
for(var i=0;i<criteria.length;i++){
let criteriaEle = criteria[i];
return Object.keys(criteriaEle).forEach(function(key){
if(obj[key] == criteriaEle[key]){
return obj;
}
})
}
})
}

例如:

object = [{type:1,company:1,color:0,name:a},{type:2,company:1,color:0,name:b},{type:1,company:3,color:0,name:c},{type:4,company:1,color:0,name:d},{type:1,company:1,color:1,name:e}]

criteria = [{type:1,company:1,color:0},{type:1,company:1,color:1}]

所以如果我将这两个数组提供给它应该返回的函数

obj = [{{type:1,company:1,color:0,name:a},{type:1,company:1,color:1,name:e}}]

我不确定我哪里出错了。请帮忙。

更新:此外,我不想使用 obj.type 或 obj.company 或 object.color 作为参数进行搜索,因为我想让我的代码易于维护,并且不想在以后添加更多条件时来更新它。

最佳答案

const data = [{type:1,company:1,color:0,name:'a'},{type:2,company:1,color:0,name:'b'},{type:1,company:3,color:0,name:'c'},{type:4,company:1,color:0,name:'d'},{type:1,company:1,color:1,name:'e'}];

const criteria = [{type:1,company:1,color:0},{type:1,company:1,color:1}];

function checkCriteria(obj) {
return criteria.some(criterion => {
for (const key in criterion) {
if (criterion[key] !== obj[key]) {
return false;
}
}
return true;
});
}

const filtered = data.filter(checkCriteria);

console.log('Filtered array: ', filtered);

这是一种解决方案。

这里有一些引用

Array.some Array.filter

根据评论,添加另一个片段来解释闭包的概念。

const data = [{type:1,company:1,color:0,name:'a'},{type:2,company:1,color:0,name:'b'},{type:1,company:3,color:0,name:'c'},{type:4,company:1,color:0,name:'d'},{type:1,company:1,color:1,name:'e'}];

function createCriteriaValidationFunction(criteria) {
return function checkCriteria(obj) {
return criteria.some(criterion => {
for (const key in criterion) {
if (criterion[key] !== obj[key]) {
return false;
}
}
return true;
});
}
}

const criteria = [{type:1,company:1,color:0},{type:1,company:1,color:1}];

const filtered = data.filter(createCriteriaValidationFunction(criteria));

console.log('Filtered array: ', filtered);

它和以前的概念是一样的,但是,标准是在文件中定义的。这一次,标准可以在外部定义并可以传递给函数。诀窍是使用传入并在闭包中可用的标准动态创建 checkCriteria 函数。在这两种情况下,条件变量在执行 checkCriteria 的范围内可用。

关于arrays - 使用另一个 JSON 数组 Node js 搜索 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46556155/

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