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

如何判断一个对象的所有值是否存在于另一个对象中

How to Implement the isPresent Function for Object Key-Value Matching

Got it, let's solve this problem. You need a function isPresent that returns true only if every key-value pair from the first object exists exactly as-is in the second object. If any key is missing from the second object, or any value doesn't match strictly, it should return false.

Here's a straightforward implementation:

function isPresent(sourceObj, targetObj) {
  // Loop through every key in the source object
  for (const key in sourceObj) {
    // Skip inherited properties (optional, but good practice)
    if (!sourceObj.hasOwnProperty(key)) continue;
    
    // Check two things: key exists in target, and values are strictly equal
    if (!(key in targetObj) || sourceObj[key] !== targetObj[key]) {
      return false;
    }
  }
  // All key-value pairs matched successfully
  return true;
}

Let's test it with your examples:

const object1 = { letter: 'a', number: 1 };
const object2 = { letter: 'b', number: 2 };
const object3 = { letter: 'a', number: 1, address: 'not in object4' };
const object4 = { letter: 'a', number: 1, address: 'different address', section: 'abc' };

// Expected true: all of object1's key-values are in object4
console.log(isPresent(object1, object4)); 

// Expected false: object2's values don't match object4's
console.log(isPresent(object2, object4)); 

// Expected false: object3's 'address' value doesn't match object4's
console.log(isPresent(object3, object4)); 

How this works:

  • We use a for...in loop to iterate over all properties in the source object. Adding hasOwnProperty ensures we only check properties directly defined on the object (not inherited ones, which is usually what you want).
  • For each key, we first verify the target object contains the key (key in targetObj), then check if the values are strictly equal (===—this ensures both the value and type match, avoiding unexpected behavior like 1 == '1' returning true).
  • As soon as we find a mismatch or missing key, we return false immediately. If we make it through all keys without issues, we return true.

Edge case note:

If your source object is empty ({}, no key-value pairs), this function will return true because there's nothing to check. If you want to treat empty source objects as a false case, add this line at the start of the function:

if (Object.keys(sourceObj).length === 0) return false;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:54:32