js根据对象某一属性去重,保证对象某一属性的唯一性

 JavaScript  2020-07-29  admin  27  36

根据对象某一属性去重,保证对象某一属性的唯一性

            /**
             * 根据对象某一属性去重,保证对象某一属性的唯一性
             * @param obj
             * @param field
             * @returns {[]}
             * @author centphp.com
             */
            function objectUnique(obj, field) {
                let result = [];
                let temp = {};
                for (let i = 0, len = obj.length; i < len; i++) {
                    if (!temp[obj[i][field]]) {
                        result.push(obj[i]);
                        temp[obj[i][field]] = true;
                    }
                }
                return result;
            }

测试:

var demoObj = [{
                "id": 10,
                "name": "aaa"
            }, {
                "id": 11,
                "name": "centphp"
            }, {
                "id": 12,
                "name": "学习"
            }, {
                "id": 10,
                "name": "centphp.com"
            }, {
                "id": 13,
                "name": "centphp"
            }, {
                "id": 14,
                "name": "学习"
            }];
            let result = objectUnique(demoObj, 'name');
            console.log(result); 
            // [{"id":10,"name":"aaa"},{"id":11,"name":"centphp"},{"id":12,"name":"学习"},{"id":10,"name":"centphp.com"}]