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