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

JS中不使用循环判断对象B的键是否存在于对象A的方法

Solution Without Explicit Loops

You can achieve this using JavaScript's array method every() combined with Object.keys()—this abstracts away the loop logic so you don't have to write a manual for/while loop yourself. Here's how it works:

var a = {name1: "hello", game1: "no games", name2: "world"};
var b = {name1:'hello world'};

// Check if all keys in b exist in a
const allKeysExist = Object.keys(b).every(key => a.hasOwnProperty(key));
console.log(allKeysExist); // Output: true

Breakdown:

  1. Object.keys(b) retrieves all enumerable string keys from object b as an array.
  2. The every() method tests whether all elements in the array pass the provided function. It stops iterating immediately if it finds a key that fails the test.
  3. The arrow function checks if a has the current key using hasOwnProperty(), which ensures we only check direct properties of a (not inherited ones from the prototype chain).

Edge Cases to Consider:

  • If b is an empty object, every() will return true (since there are no keys to fail the check).
  • If you need to include non-enumerable keys in your check, replace Object.keys(b) with Object.getOwnPropertyNames(b).
  • If your objects use symbol keys, use Reflect.ownKeys(b) instead—it captures both string and symbol keys, regardless of whether they're enumerable.

Example with a failing case (when b has a key not present in a):

var b = {name1:'hello world', name3: 'test'};
const allKeysExist = Object.keys(b).every(key => a.hasOwnProperty(key));
console.log(allKeysExist); // Output: false

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:12:03