-
Notifications
You must be signed in to change notification settings - Fork 26
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
对比两个对象是否相等 #48
Comments
function compareObject(obj1,obj2) {
var list = [];
for(var key in obj1){
if(typeof obj1[key] === "object"){
var newlist = compareObject(obj1[key],obj2[key])
newlist = newlist.map(function (value) {
return key + "." +value
})
list = list.concat(newlist)
}else if(obj1[key] !== obj2[key]){
list.push(key)
}
}
if(list.length===0){
return true
}return list
} |
function compareObject(obj1,obj2) {
var list = [];
for(var key in obj1){
if(typeof obj1[key] === "object"){
var newlist = compareObject(obj1[key],obj2[key])
if( Object.prototype.toString.call(newlist) === "[object Array]"){
newlist = newlist.map(function (value) {
return key + "." +value
})
list = list.concat(newlist)
}
}else if(obj1[key] !== obj2[key]){
list.push(key)
}
}
return list.length == 0? true:list
} |
function compareObject(obj1, obj2) {
if(JSON.stringify(obj1) === JSON.stringify(obj2)){
return true;
}else {
var result = [];
for(var key in obj1){
if(typeof obj1[key] === "object"){
var array = compareObject(obj1[key],obj2[key])
array = array.map(function (value) {
return key + "." +value
})
result = result.concat(array)
}else if(obj1[key] !== obj2[key]){
result.push(key)
}
}
return result;
}
} |
function compareObject(object1,object2){
var arr = [];
for(var i in object1){
for(var j in object2){
if(i == j && object1[i] != object2[j]){
if(object1[i] instanceof Object){
if(object2[j] instanceof Object){
for(var x in object1[i]){
for(var y in object2[j]){
if(x == y && object1[i][x] != object2[j][y]){
arr.push(i +"."+ x);
}
}
}
}else{
arr.push(i);
}
}else{
arr.push(i);
}
}
}
}
document.write(arr);
}
compareObject(object1,object2); |
不知道是以 obj1 的 key 为基准还是所有 key function merge(keys1, keys2){
var keys = [].concat(keys1);
keys2.forEach(function (i){
if (keys.indexOf(i) === -1){
keys.push(i);
}
});
return keys;
}
function compareObject(obj1, obj2){
var keys1 = Object.keys(obj1);
var keys2 = Object.keys(obj2);
var keys = merge(keys1, keys2);
var result = [];
keys.forEach(function (key){
if (typeof obj1[key] === 'object' && typeof obj2[key] === 'object'){
var children = compareObject(obj1[key], obj2[key]);
if (children !== true) {
children = children.map(function (i){
return key + '.' + i;
});
result = result.concat(children);
}
}else if (obj1[key] !== obj2[key]) {
result.push(key);
}
});
return !result.length ? true : result;
}
|
这个代码放在浏览器里面运行报错,代码如下:
} |
深入对比两个对象(key相同)value是否相等,如果相等返回true,如果不等,返回不相等的字段的key用
.
分隔,The text was updated successfully, but these errors were encountered: