You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript测试中如何对比object1所有字段是否存在于object2中?

How to Verify Object1 is a Subset of Object2 (Test Framework Solutions)

Hey there! Sounds like you need to confirm that every field and its matching value from object1 exists in object2—even if object2 has extra properties you don't care about. Instead of building a custom comparison function from scratch, most popular test frameworks have built-in utilities that do this perfectly for you. Let me break down the options:

Jest

Jest has a purpose-built matcher called toMatchObject() that does exactly what you need. It checks that all properties (and nested properties) from your target object (object1) exist in the source object (object2), ignoring any extra fields in object2.

Here's how you'd use it with your example:

const object1 = { user: { id: 25, name: "Elon" } };
const object2 = { user: { id: 25, name: "Elon", role: "admin" }, rules: [ "edit" ] };

test("All fields from object1 exist in object2", () => {
  expect(object2).toMatchObject(object1); // This passes!
});

This works recursively for nested objects, so your nested user object gets compared correctly without extra code.

Chai

If you're using the Chai assertion library, you can use the deep.include assertion. The deep flag ensures nested objects are checked recursively, and include verifies all properties from object1 are present in object2 with matching values.

Example code:

const chai = require('chai');
const expect = chai.expect;

const object1 = { user: { id: 25, name: "Elon" } };
const object2 = { user: { id: 25, name: "Elon", role: "admin" }, rules: [ "edit" ] };

expect(object2).to.deep.include(object1); // This passes!

Bonus: Custom Function (If You Prefer)

While the test framework utilities are recommended (they handle edge cases like arrays, null values, and special data types better), here's a quick recursive function if you want to roll your own:

function compareFn(obj1, obj2) {
  for (const key in obj1) {
    // Check if the key exists in object2
    if (!(key in obj2)) return false;
    
    const val1 = obj1[key];
    const val2 = obj2[key];
    
    // Recursively check nested objects
    if (typeof val1 === 'object' && val1 !== null) {
      if (!compareFn(val1, val2)) return false;
    } 
    // Compare primitive values
    else if (val1 !== val2) {
      return false;
    }
  }
  return true;
}

// Usage
compareFn(object1, object2); // Returns true

内容的提问来源于stack exchange,提问作者Jackson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:28:56