gpt4 book ai didi

javascript - TypeError : obj[key]. 包括不是一个函数:在过滤器函数中

转载 作者:行者123 更新时间:2023-12-02 23:42:39 25 4
gpt4 key购买 nike

我想找到具有某种值(value)的任何属性的对象。但我有错误: TypeError: obj[key].includes 不是函数。如何解决?

var aa = [{id: 1,type: 1,status: 1,name: 'txt'},{id: 2,type: 1,status: 1,name: 'txt'},{id: 3,type: 0,status: 0,name: 'txt'}];

function filterIt(arr, searchKey) {
return arr.filter(function(obj) {
return Object.keys(obj).some(function(key) {
return obj[key].includes(searchKey);
})
});
}

filterIt(aa, 'txt');

最佳答案

尝试使用Object.values代替:

var aa = [{id: 1,type: 1,status: 1,name: 'txt'},{id: 2,type: 1,status: 1,name: 'txt'},{id: 3,type: 0,status: 0,name: 'txt'}];

function filterIt(arr, searchKey) {
return arr.filter(function(obj) {
return Object.values(obj).includes(searchKey);
});
}

console.log(filterIt(aa, 'txt'));
.as-console-wrapper { max-height: 100% !important; top: auto; }

您还可以使此代码更加紧凑:

var aa = [{id: 1,type: 1,status: 1,name: 'txt'},{id: 2,type: 1,status: 1,name: 'txt'},{id: 3,type: 0,status: 0,name: 'txt'}];

const filterIt = (arr, searchKey) => arr.filter(obj => Object.values(obj).includes(searchKey));

console.log(filterIt(aa, 'txt'));
.as-console-wrapper { max-height: 100% !important; top: auto; }

关于javascript - TypeError : obj[key]. 包括不是一个函数:在过滤器函数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55997331/

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