我想比较两个 json 对象,不包括其中一个键

发布于 2025-01-11 07:10:46 字数 268 浏览 0 评论 0原文

我有两个对象 x,y,我想比较这两个对象,不包括其中一个键“c”

let x = {a: 5, b: 6, c: "string"}
let y = {a: 5, b: 8, c: "string"}

我想如何比较它 -

JSON.stringify(x) === JSON.stringify(y)

上面的工作原理,但它会比较我想在此处比较时排除 c 的所有键。实现这一目标的最佳方法是什么?

I have two objects x,y and i want to compare both of these excluding one of the keys "c"

let x = {a: 5, b: 6, c: "string"}
let y = {a: 5, b: 8, c: "string"}

How i am trying to compare it is -

JSON.stringify(x) === JSON.stringify(y)

Above works but it will compare all keys I want to exclude c in comparison here. What's the best way to achieve this ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

分開簡單 2025-01-18 07:10:46

以下代码从对象x中获取所有键,从列表中删除c,然后执行比较。

let x = { a: 5, b: 6, c: "string" };
let y = { a: 5, b: 6, c: "another string" };

console.log(
  Object.keys(x)
    .filter((key) => key !== "c")
    .every((key) => x[key] === y[key])
);

The following code obtains all the keys from object x, removes c from the list, and then performs the comparison.

let x = { a: 5, b: 6, c: "string" };
let y = { a: 5, b: 6, c: "another string" };

console.log(
  Object.keys(x)
    .filter((key) => key !== "c")
    .every((key) => x[key] === y[key])
);
猫腻 2025-01-18 07:10:46

array.sort 需要一个比较器函数。你可以在这里使用完全相同的东西

function myObjComparator (x, y) {
  if (x.a != y.a) return y.a - x.a;
  return y.b - x.b;
}

array.sort requires a comparator function. You can use the exact same thing here

function myObjComparator (x, y) {
  if (x.a != y.a) return y.a - x.a;
  return y.b - x.b;
}
画离情绘悲伤 2025-01-18 07:10:46

一般来说,我不会为了比较它们而对对象进行字符串化。
原因很简单,就是必须确保成员的顺序相同,否则结果将不正确。

例如:

// objects are equals
const y = { a: '1', b: '2' }
const x = { b: '2', b: '1' }
// but result is not what you expect
JSON.stringify(x) === JSON.stringify(y) // false

但是,如果您可以确保成员的顺序始终相同,则 stringify 速度很快并且是一个不错的选择。

您可以按顺序使用扩展语法避免“c”属性

const remappedX = { ...x, c: undefined };
const remappedY = { ...y, c: undefined };
JSON.stringify(remappedX) === JSON.stringify(remappedY); // true

或者更通用

const allowedKeys = Object.keys(x).filter((k) => k !== 'c');
JSON.stringify(x, allowedKeys) === JSON.stringify(y, allowedKeys);

的方法是循环遍历对象键或条目

for(const key of Object.keys(x)) {
   if (key === 'c') {
      continue;
   }
   if (x[key] !== y[key]) {
         return false;
   }
}
return true;

但是,如果您的对象是嵌套的,则需要使用深度相等算法,这当然会更慢。

此处给出了更通用的答案

Generally, I would NOT stringify objects in order to compare them.
The reason is quite simple and is that you MUST to be sure that the order of the members are the same, otherwise the result won't be correct.

Ex:

// objects are equals
const y = { a: '1', b: '2' }
const x = { b: '2', b: '1' }
// but result is not what you expect
JSON.stringify(x) === JSON.stringify(y) // false

But, if you can ensure that the order of the members is always the same, stringify is fast and a good option.

You can use the spread syntax in order to avoid the "c" property

const remappedX = { ...x, c: undefined };
const remappedY = { ...y, c: undefined };
JSON.stringify(remappedX) === JSON.stringify(remappedY); // true

Or alternatively

const allowedKeys = Object.keys(x).filter((k) => k !== 'c');
JSON.stringify(x, allowedKeys) === JSON.stringify(y, allowedKeys);

More generic method is to loop over Object key or alternatively to entries

for(const key of Object.keys(x)) {
   if (key === 'c') {
      continue;
   }
   if (x[key] !== y[key]) {
         return false;
   }
}
return true;

But, if your object is nested, you need to use a deep equality algorithm, which is of course slower.

More generic answer has been given here

风向决定发型 2025-01-18 07:10:46

感谢大家对我的问题的快速答复,但下面是一个简单的方法,我可以通过它来实现上述逻辑

import omit from "lodash/omit";
import isEqual from "lodash/isEqual";

let x = {a: 5, b: 6, c: "string"},
y = {a: 5, b: 8, c: "string"}

result = isEqual(omit(x, ['c']), omit(y, ['c']))

Thanks everyone for quick responses on my question but below was an easy method from which I could implement the above logic

import omit from "lodash/omit";
import isEqual from "lodash/isEqual";

let x = {a: 5, b: 6, c: "string"},
y = {a: 5, b: 8, c: "string"}

result = isEqual(omit(x, ['c']), omit(y, ['c']))
夏末的微笑 2025-01-18 07:10:46

这又如何呢?

JSON.stringify(x, ['a','b']) === JSON.stringify(y, ['a','b']);

更好的解决方案:

function replacer(key, value) {
  // Filtering out properties
  if (key === 'c') {
    return undefined;
  }
  return value;
}
JSON.stringify(x, replacer) === JSON.stringify(y, replacer);

更正 更好的解决方案:

const filterKeys = (obj) => Object.keys(y).filter(k => k !== 'c').sort()
JSON.stringify(x, filterKeys(x)) === JSON.stringify(y, filterKeys(y));

What about this?

JSON.stringify(x, ['a','b']) === JSON.stringify(y, ['a','b']);

better solution:

function replacer(key, value) {
  // Filtering out properties
  if (key === 'c') {
    return undefined;
  }
  return value;
}
JSON.stringify(x, replacer) === JSON.stringify(y, replacer);

correct better solution:

const filterKeys = (obj) => Object.keys(y).filter(k => k !== 'c').sort()
JSON.stringify(x, filterKeys(x)) === JSON.stringify(y, filterKeys(y));
别靠近我心 2025-01-18 07:10:46

使用三元运算符来比较两个对象。

演示:

let x = {a: 5, b: 6, c: "string"};
let y = {a: 5, b: 8, c: "string"};

function compare(obj1, obj2) {
  return (obj1.a != obj2.a) ? false : (obj1.b != obj2.b) ? false : true;
}

console.log(compare(x, y));

通过删除不需要的属性,然后使用 JSON.stringify() 进行比较

演示:

let x = {a: 5, b: 6, c: "string"};
let y = {a: 5, b: 8, c: "string"};

delete x.c;
delete y.c;

console.log(JSON.stringify(x) === JSON.stringify(y));

Using ternary operator to compare both the objects.

Demo :

let x = {a: 5, b: 6, c: "string"};
let y = {a: 5, b: 8, c: "string"};

function compare(obj1, obj2) {
  return (obj1.a != obj2.a) ? false : (obj1.b != obj2.b) ? false : true;
}

console.log(compare(x, y));

By deleting the unwanted properties and then compare using JSON.stringify()

Demo :

let x = {a: 5, b: 6, c: "string"};
let y = {a: 5, b: 8, c: "string"};

delete x.c;
delete y.c;

console.log(JSON.stringify(x) === JSON.stringify(y));

变身佩奇 2025-01-18 07:10:46

这是一个解决方案

const x = {a: 5, b: 8, c: "string1", d: {e: 9}}
const y = {a: 5, b: 8, c: "string2", d: {e: 9}}

const compare = (obj1, obj2, except = []) => {
    
    if (Object.keys(obj1).length < Object.keys(obj2).length) {
        [obj1, obj2] = [obj2, obj1];
    }
    
    for (const obj1Key in obj1) {
        if (except.includes(obj1Key)) continue;

        if (!obj2.hasOwnProperty(obj1Key)) return false;

        if (typeof obj1[obj1Key] === 'object') {
            if (typeof obj2[obj1Key] !== 'object') return false;
            
            const isEqual = compare(obj1[obj1Key], obj2[obj1Key]);
            
            if (isEqual) continue
            
            return false;
        }

        if (obj1[obj1Key] !== obj2[obj1Key]) return false;
    }
    
    return true;
}

console.log(compare(x, y, ['c']));

Here is a solution

const x = {a: 5, b: 8, c: "string1", d: {e: 9}}
const y = {a: 5, b: 8, c: "string2", d: {e: 9}}

const compare = (obj1, obj2, except = []) => {
    
    if (Object.keys(obj1).length < Object.keys(obj2).length) {
        [obj1, obj2] = [obj2, obj1];
    }
    
    for (const obj1Key in obj1) {
        if (except.includes(obj1Key)) continue;

        if (!obj2.hasOwnProperty(obj1Key)) return false;

        if (typeof obj1[obj1Key] === 'object') {
            if (typeof obj2[obj1Key] !== 'object') return false;
            
            const isEqual = compare(obj1[obj1Key], obj2[obj1Key]);
            
            if (isEqual) continue
            
            return false;
        }

        if (obj1[obj1Key] !== obj2[obj1Key]) return false;
    }
    
    return true;
}

console.log(compare(x, y, ['c']));

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文