给定两个javascript对象,如何确定哪些字段已更改?

时间:2017-04-12 03:45:33

标签: javascript

假设我有两个版本:

set.seed(24)
data <- as.data.frame(matrix(sample(c(-1, 0, 4, 3, NA), 25, replace=TRUE), 5, 5)) 

如果let oldObj = { name: "john", location: "usa", age: 43 } let newObj = { name: "john", location: "usa", age: 44 } 已更改。

3 个答案:

答案 0 :(得分:0)

假设您只想跟踪(原始值)的更改而不是添加/删除,您可以只迭代一个对象的值并直接与另一个对象中的相应值进行比较:

&#13;
&#13;
let oldObj = {
    name: "john",
    location: "usa",
    age: 43
}

let newObj = {
    name: "john",
    location: "usa",
    age: 44
}

let changes = Object
  .entries(oldObj)
  .filter(([key, value]) => value !== newObj[key])

console.log(changes)
&#13;
&#13;
&#13;

如果您不关心这些值,您只需过滤掉密钥:

&#13;
&#13;
let oldObj = {
    name: "john",
    location: "usa",
    age: 43
}

let newObj = {
    name: "john",
    location: "usa",
    age: 44
}

let changes = Object
  .keys(oldObj)
  .filter(key => oldObj[key] !== newObj[key])

console.log(changes)
&#13;
&#13;
&#13;

如果要包含添加/删除,可以先使用更多的键确定对象,并按上述方式执行:

&#13;
&#13;
let oldObj = {
    name: "john",
    location: "usa",
    age: 43
}

let newObj = {
    name: "john",
    location: "usa",
    age: 44,
    addition: 'test'
}

let [larger, smaller] = Object.keys(oldObj).length > Object.keys(newObj).length
  ? [oldObj, newObj]
  : [newObj, oldObj]

let changes = Object
  .entries(larger)
  .filter(([key, value]) => !smaller.hasOwnProperty(key) || value !== smaller[key])

console.log(changes)
&#13;
&#13;
&#13;

答案 1 :(得分:0)

Hooray for Lodash

var changes = _.reduce(oldObj, function(result, value, key) {
    return _.isEqual(value, newObj[key]) ?
        result : result.concat(key);
}, []);
console.log(changes);

答案 2 :(得分:0)

你应该做的第一件事是编辑你的问题,并用其他东西替换new,因为new是javascript中的一个关键字,用于构造函数来创建该特定构造函数的实例。

let old = {
    name: "john",
    location: "usa",
    age: 43
}

let _new = {
    name: "john",
    location: "usa",
    age: 44
}
for ( let j in old ) {
    if ( old[j] !== _new[j] ) {
        console.log(`${old[j]} is not ${_new[j]}`);
    }
}

下面的代码遍历old对象,j的内容将是旧对象的键,if语句使用old[j]来获取j键的内容(同样适用于_new[j]),if语句还会检查_new[j]_old[j]的内容和类型是否相同。如果您不关心类型,则应删除if语句中的一个等号