我有2个对象,其中一个以另一个对象的副本开头。我希望能够检查不同的值是否已更改,即它们不再匹配:
var obj = {
key1: {
innerKey: "val"
},
key2: "matching val"
};
var copy = {
key1: {
innerKey: "non-matching val"
},
key2: "matching val"
};
我希望有某种hasChanged()
方法可以解决以下问题:
hasChanged(obj.key1.innerKey); // result true
hasChanged(obj.key2); // result false
似乎我需要一些方法来获取属性的“路径”或位置,以便在另一个对象上找到该属性进行比较,但我不知道如何去做。
由于
答案 0 :(得分:1)
$.fn.hasChanged = function(obj,key){
var origObj = this[0];
var originalValue = Object.byString(origObj,key);
var currentValue = Object.byString(obj,key);
return !(originalValue == currentValue);
};
Object.byString = function(o, s) {
s = s.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties
s = s.replace(/^\./, ''); // strip a leading dot
var a = s.split('.');
for (var i = 0, n = a.length; i < n; ++i) {
var k = a[i];
if (k in o) {
o = o[k];
} else {
return;
}
}
return o;
}
var obj = {
key1: {
innerKey: "val"
},
key2: "matching val"
};
var copy = {
key1: {
innerKey: "non matching val"
},
key2: "matching val"
};
alert($(obj).hasChanged(copy,'key1.innerKey'));
alert($(obj).hasChanged(copy,'key2'));
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
答案 1 :(得分:1)
lodash library看起来就像我在这里找到的那样:
_.get(obj, path);
e.g。 _.get(obj,'key1.innerKey'); //“val”
这样:
function hasChanged(obj, backup, path) {
var objVal = _.get(obj, path);
var backupVal = _.get(backup, path);
return objVal !== backupVal;
}