我有一个搜索数组对象的函数,它将检查数组中的所有对象是否具有相同的属性名称。我已经制定了以下解决方案,但我想知道我的方法是否存在任何潜在的陷阱或更简单的方法。
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));
答案 0 :(得分:2)
您不必保留对象属性的数组,而是使用.hasOwnProperty()
和.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;
}