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:
Object.keys(b)retrieves all enumerable string keys from objectbas an array.- 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. - The arrow function checks if
ahas the current key usinghasOwnProperty(), which ensures we only check direct properties ofa(not inherited ones from the prototype chain).
Edge Cases to Consider:
- If
bis an empty object,every()will returntrue(since there are no keys to fail the check). - If you need to include non-enumerable keys in your check, replace
Object.keys(b)withObject.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
相关产品推荐
相关产品推荐

