欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-07-12 14:14:20
...

前言

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


一、当条件为单个时

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"]]
相关标签: js