Javascript 检索按指定键过滤的所有对象';s值
我在获取准确的输出时遇到了一些问题Javascript 检索按指定键过滤的所有对象';s值,javascript,json,filter,lodash,Javascript,Json,Filter,Lodash,我在获取准确的输出时遇到了一些问题 const data = [{ name: 'Alex Young', country: 'SE', nID: 424 address: 'some address 12' },{ name: 'Martha Lewis', country: 'PT', nID: 312, address: 'an address 49' },{ name: 'Sophie Jones', cou
const data = [{
name: 'Alex Young',
country: 'SE',
nID: 424
address: 'some address 12'
},{
name: 'Martha Lewis',
country: 'PT',
nID: 312,
address: 'an address 49'
},{
name: 'Sophie Jones',
country: 'NL',
nID: 36,
address: 'other address 3129'
}];
const filter = '12';
const keysToEvaluate = ['name', 'country', 'address'];
对于给定的数据,我只想计算给定的keystevaluate,并输出值包含过滤器的所有对象
预期产出:
[{
name: 'Alex Young',
country: 'SE',
nID: 424
address: 'some address 12'
},{
name: 'Sophie Jones',
country: 'NL',
nID: 36,
address: 'other address 3129'
}]
TIA
const data=[{name:'Alex Young',country:'SE',nID:424,address:'some address 12'},{name:'Martha Lewis',country:'PT',nID:312,address:'an address 49'},{name:'Sophie Jones',country:'NL nID:36,address:'other address 3129'};
常量过滤器='12';
常量keystevaluate=['name','country','address'];
const filtered=data.filter(t=>keystevaluate.some(k=>String(t[k])。includes(filter));
console.log(过滤)有关按对象属性筛选数组以及使用变量访问对象属性的信息,请参见。基本上:const result=array.filter(entry=>keystevaluate.some(key=>entry[key].includes(filter))代码>我假设任何匹配都意味着应该包括该对象。如果所有属性都与要保留的对象匹配,请将some
更改为every
。调整它使其变得不区分大小写:const filtered=data.filter(t=>keystevaluate.some(k=>String(t[k].toLowerCase())。includes(filter.toLowerCase())代码>