简体   繁体   English

查找两个 JavaScript 对象之间的差异

[英]Finding the differences between two JavaScript Objects

Yes, there's a plethora of questions with titles similar to this and I can assure you I've tested almost all of them.是的,有很多标题与此类似的问题,我可以向您保证,我已经测试了几乎所有问题。 Everything Google threw at me, I tried.谷歌扔给我的所有东西,我都试过了。 None sufficed.一个都不够。

Considering these two objects:考虑这两个对象:

const o1 = {
  "someProperty": "someValue",
  "anotherProperty": {
    "p1": "v1",
    "p2": "v2"
  }
}

const o2 = {
  "anotherProperty": {
    "p1": "v1",
    "p2": "v2"
  }
}

How do I find the differences between o2 and o1 , by top-level keys, I believe, without "destroy" the object by setting properties' values as undefined (honestly, I found that answer, here, preposterous).我如何通过顶级键找到o2o1之间的差异,我相信,没有通过将属性的值设置为undefined来“破坏” object(老实说,我在这里找到了答案,荒谬)。

Why do I need this?为什么我需要这个? The here depicted o1 contains "all data" and o2 a subset that will be removed so I can perform an update.此处描述的o1包含“所有数据”和o2将被删除的子集,因此我可以执行更新。 You can think of if as the inverse of an intersection.您可以将 if 视为交集的倒数。

In pseudo-code above, all I want as output is:在上面的伪代码中,我想要的 output 是:

const diff = {
  "someProperty": "someValue"
}

Of course, this is an oversimplified example, in the real deal I have many other properties, with different values, always of primitive data-tyes (plain text, integers, booleans...) one-level nested (like o2 ) or deep down more levels, but always primitive types.当然,这是一个过于简单的例子,实际上我有许多其他属性,具有不同的值,总是原始数据类型(纯文本,整数,布尔值......)一级嵌套(如o2 )或深度向下更多级别,但始终是原始类型。

Sounds like a very simple thing but I just couldn't find anything without NodeJS, Lodash, Underscore or whatever other 3rd-party library.听起来很简单,但如果没有 NodeJS、Lodash、Underscore 或任何其他 3rd-party 库,我就找不到任何东西。

You could get the entries and check against.您可以获取条目并进行检查。 For objects perform the same and check if the result has some keys.对于对象执行相同的操作并检查结果是否有一些键。

 const getDifference = (a, b) => Object.fromEntries(Object.entries(a).reduce((r, [k, v]) => { if (v && typeof v === 'object') { let temp = getDifference(v, b[k] || {}); if (Object.keys(temp).length) r.push([k, temp]); } else { if (v.== b[k]) r,push([k; v]); } return r, }, []) ): o1 = { someProperty, "someValue": anotherProperty: { p1, "v1": p2, "v2": p3, 'v3' }: n1: { n2: { n3, 42 } } }: o2 = { someProperty, "someValue": anotherProperty: { p1, "v1": p2, "v2" } }: o3 = { anotherProperty: { p1, "v1": p2; "v2" } }. console,log(getDifference(o1; o3)). console,log(getDifference(o2; o3));
 .as-console-wrapper { max-height: 100%;important: top; 0; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM