过滤对象列表

问题描述:

我使用Redux呈现了一个列表,并且有一个搜索字段来查找包含搜索关键字的影片。我的列表是一个不是数组的对象,如果用户键入:“The”,它应该过滤标题中有'The'的列表。过滤对象列表

{'1': { 'title': 'A Name' },'2': { 'title': 'The Name' },'3': { 'title': 'The Second Name' }} 

所以过滤后的结果应该是

{'2': { 'title': 'The Name' },'3': { 'title': 'The Second Name' }} 

你会怎么做呢?使用lodash是一项奖励。 感谢

+1

在你的问题中的对象是无效的。你能确保你给出了正确的对象吗? –

您礁使用_.pickBy()为对象的过滤器,检查还没有测试过,如果每个子对象标题_.includes()搜索词:

const data = {'1': { 'title': 'A Name' }, '2': { 'title': 'The Name' }, '3': { 'title': 'The Second Name' }}; 
 

 
const result = _.pickBy(data, (v) => _.includes(v.title, 'The')); 
 

 
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

let filteredList = []; 
    _.forEach(responseList, function(value) { 
     var titleToSearch = value.title.split(" "); 
     if(titleToSearch [0]=="The") 
      filteredList.push(value); 
    }); 

请试试这个逻辑,尽管

你需要迭代你的对象键,过滤并将结果减少回到对象。

const obj = {'1': { 'title': 'A Name' },'2': { 'title': 'The Name' },'3': { 'title': 'The Second Name' }} 
 

 
console.log(
 
    Object.keys(obj) 
 
    .filter(key => obj[key].title.includes('The')) 
 
    .reduce((acc, key) => (acc[key] = obj[key], acc), {}) 
 
)

或者使用lodash#变换

const obj = {'1': { 'title': 'A Name' },'2': { 'title': 'The Name' },'3': { 'title': 'The Second Name' }} 
 

 
console.log(
 
    _.transform(obj, (result, value, key) => { 
 
    if(value.title.includes('The')) result[key] = value 
 
    }, {}) 
 
)
<script src="https://unpkg.com/[email protected]"></script>