找出数组中符合某些条件的对象数组

前言

过滤出符合某些条件的数组

一、当条件为单个时

const data = [
			{ id: 1,topic: '难过',title: '再见只是陌生人' },
            { id: 2,topic: '遗憾',title: '落空'},
            { id: 3,topic: '回忆',title: '那女孩对我说' }
        ]
function filterData(data, params) { 
       let _data = data.filter(item => item[params] === 2)
       return _data
  }
 console.log(filterData(data, 'id'))  //[{id: 2, topic: "遗憾", title: "落空"}]

二、当条件为对象时

 const data = [{ 
                topic_id: 1,
                topic_name: '侧脸',
                first_class_category: '歌曲',
                second_class_category: '回忆',
                reviewing: 1,
                reviewed: 23,
                filtered: 111,
                effective_date: '2020-12-20 00:06:00',
                review_status: 'reviewing',
                online_status: 'offline',
                owner: '于果',
            },
            { 
                topic_id: 2,
                topic_name: '小幸运',
                first_class_category: '音乐',
                second_class_category: '青春',
                reviewing: 2,
                reviewed: 33,
                filtered: 121,
                effective_date: '2020-12-20 00:06:00',
                review_status: 'filtered',
                online_status: 'offline',
                owner: '田馥甄',
            },
            { 
                topic_id: 3,
                topic_name: '光年之外',
                first_class_category: '歌曲',
                second_class_category: '天籁之音',
                reviewing: 3,
                reviewed: 53,
                filtered: 151,
                effective_date: '2020-12-20 00:06:00',
                review_status: 'reviewed',
                online_status: 'online',
                owner: '邓紫棋',
            },
        ]

        function filterData(data, obj) { 
            return data.filter(item => { 
                return Object.entries(obj).every(([_key, _val]) => { 
                    if (item[_key] === _val) return true
                })
            })
        }
        let obj = { 
            first_class_category: '歌曲',
            review_status: 'reviewed'
        }
        console.log(filterData(data, obj)) 
        //[{effective_date: "2020-12-20 00:06:00",filtered: 151,first_class_category: "歌曲",online_status: "online",owner: "邓紫棋",review_status: "reviewed",reviewed: 53,reviewing: 3,second_class_category: "天籁之音",topic_id: 3,topic_name: "光年之外"}]

总结

Ojbect.entries()返回可枚举属性的键值对数组
例如:

	let obj1 = { 
            id: 1,
            topic: '难过',
            title: '再见只是陌生人'
        }
    console.log(Object.entries(obj)) //[["first_class_category", "歌曲"],["review_status", "reviewed"]]
    原文作者:I'm Lena !
    原文地址: https://blog.csdn.net/qq_41329302/article/details/108404236
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞