Javascript 两个物体之间的局部深度比较
使用JavaScript实现两个对象的深度是comapre,如果true不等于equal返回值,则返回false。第一个参数与原始对象比较,第二个参数用于与目标对象比较,对象属性只存在于值中,属性不存在于原始对象中,如果对象存在,则直接返回false。这里有一些例子Javascript 两个物体之间的局部深度比较,javascript,json,Javascript,Json,使用JavaScript实现两个对象的深度是comapre,如果true不等于equal返回值,则返回false。第一个参数与原始对象比较,第二个参数用于与目标对象比较,对象属性只存在于值中,属性不存在于原始对象中,如果对象存在,则直接返回false。这里有一些例子 const object = { id: 1, name: 'test', product: { id: 1, name: 'product' }, updat
const object = {
id: 1,
name: 'test',
product: {
id: 1,
name: 'product'
},
updatedAt: 'now'
};
const objectA = {
name: 'test',
product: {
name: 'product'
}
};
const objectB = {
name: 'test',
product: {
name: 'anotherProduct'
}
};
compare(object, objectA) // return true
compare(object, objectB) // return false
这是我提出的解决方案, 小提琴- 它具有递归函数,可以检查给定的两个对象是对象还是隐式对象 如果是对象,它将再次递归检查它们是否相同。 比较函数的代码 它为你的目标工作
function compare(first,second)
{
//alert("once");
var flag=true;
if(typeof second=='object')
{
//if the variable is of type object
if(typeof first!='object')
{
flag=false
}
else
{
//check every key of object
$.each(second, function(key, value) {
//if socond's key is available in first.
if(first.hasOwnProperty(key))
{
//recursive call for the value.
if(!compare(first[key],second[key]))
{
flag=false;
}
}
else
{
flag=false
}
});
}
}
else
{
// if two objects are int,string,float,bool.
if(first!=second)
{
flag=false;
}
}
return(flag);
}