0

我有一个函数可以搜索数组对象并检查数组中的所有对象是否具有相同的属性名称。我已经制定了以下解决方案,但我想知道我的方法是否存在任何潜在的陷阱或更简单的方法。

var objects = [{
                name: 'jon',
                department: 'HR',
                experience: 1
            }, {
                name: 'meg',
                department: 'billing',
                experience: 2
            }, {
                name: 'tom',
                department: 'accounts',
                experience: 3
            }];


            function isArrayCongruent(array) {
                //array to check congruency
                var objArray = [];
                //return bool for congruency or no
                var flag = false;
                //create array of property names
                for (var i = 0; i < array.length; i++) {
                    var o = [];
                    for (var props in array[i]) {
                        o.push(props);
                    }
                    objArray.push(o);
                }
                //get the count of properties from the first element
                var propCount = objArray[0].length;
                var propList = objArray[0] + '';
                //start comparing elements at second array element
                for (var j = 1; j < objArray.length; j++) {
                    if (propCount === objArray[j].length) {
                        //turn list of properties in into a string for ease of comparison
                        if (propList === objArray[j] + '') {
                            flag = true;
                        }
                        else {
                            flag = false;
                        }
                        flag = true;
                    }
                    else {
                        flag = false;
                    }
                }
                return flag;
            };
            console.log(isArrayCongruent(objects));
4

1 回答 1

2

您不必保留对象属性的数组,使用.hasOwnProperty()and.getOwnPropertyNames()代替:

function isArrayCongruent(array) {
    var pattern = array[0];
    var patternPropertiesCount = Object.getOwnPropertyNames(pattern).length;
    for (var i = 1; i < array.length; i++) {
        var current = array[i];
        if (Object.getOwnPropertyNames(current).length !== patternPropertiesCount) {
            return false;
        }
        for (var prop in current) {
            if (!pattern.hasOwnProperty(prop)) return false;
        }
    }
    return true;
}

小提琴

于 2013-10-28T16:41:43.673 回答