If I have two associative arrays, what would be the most efficient way of doing a diff against their values?
For example, given:
array1 = {
for
This might be much more sophisticate than what you need, but you can try my jsondiffpatch lib that will diff any pair of javascript objects:
https://github.com/benjamine/jsondiffpatch
if you want to test it you can see it live in http://benjamine.github.com/jsondiffpatch/demo/index.html
Try this:
function diff(obj1, obj2) {
var result = {};
$.each(obj1, function (key, value) {
if (!obj2.hasOwnProperty(key) || obj2[key] !== obj1[key]) {
result[key] = value;
}
});
return result;
}
A minha ficou assim:
function diff(obj1, obj2){
var result = {};
for(var key1 in obj1){
let resposta = {
before : obj1[key1] ? obj1[key1] : '',
after : obj2[key1] ? obj2[key1] : ''
};
if(resposta.before !== resposta.after){
result[key1] = resposta;
}
}
for(var key2 in obj2){
if(!(key2 in result) || (key2 in obj1)){
let resposta = {
before : obj1[key2] ? obj1[key2] : '',
after : obj2[key2] ? obj2[key2] : ''
}
if(resposta.before !== resposta.after){
result[key2] = resposta;
}
}
}
return (Object.assign({}, result));
}
RaYell's solution is nice but unfortunately will only tell you the items in obj2 that are either different from or non-existant in obj1, if we need to know both sides, let's get all keys and then compare. The following function will return an associative array with key values for each object. Oh... to be fair, I haven't tested yet, but this should work.
var diff = function(obj1,obj2) {
var newObj = $.extend({},obj1,obj2);
var result = {};
$.each(newObj, function (key, value) {
if (!obj2.hasOwnProperty(key) || !obj1.hasOwnProperty(key) || obj2[key] !== obj1[key]) {
result[key] = [obj1[key],obj2[key]];
}
});
return result;
}
Oh, and while I do recognize that the first solution answered the initial question, I think the above solution offers another approach that the initial user might find useful so as to not require checking twice.
If you're familiar with PHP syntax, take a look at http://phpjs.org/functions/index which includes almost all PHP's array related functions converted into JavaScript – including array_diff