Finding Common Object Keys in JavaScript

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will be exploring a JavaScript function that helps us find the common keys between two objects. We will use the Object.keys() method to get the keys of the first object, and then check if the second object has a key that matches using Object.prototype.hasOwnProperty(). Finally, we will use Array.prototype.filter() to filter out the keys that are not common to both objects. By the end of this lab, you will have a solid understanding of how to efficiently find common keys between two objects in JavaScript.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") javascript/AdvancedConceptsGroup -.-> javascript/destr_assign("`Destructuring Assignment`") subgraph Lab Skills javascript/variables -.-> lab-28203{{"`Finding Common Object Keys in JavaScript`"}} javascript/data_types -.-> lab-28203{{"`Finding Common Object Keys in JavaScript`"}} javascript/arith_ops -.-> lab-28203{{"`Finding Common Object Keys in JavaScript`"}} javascript/comp_ops -.-> lab-28203{{"`Finding Common Object Keys in JavaScript`"}} javascript/higher_funcs -.-> lab-28203{{"`Finding Common Object Keys in JavaScript`"}} javascript/destr_assign -.-> lab-28203{{"`Finding Common Object Keys in JavaScript`"}} end

Tips for Coding and Finding Common Keys

To practice coding, open the Terminal/SSH and type node.

To find the common keys between two objects, follow these steps:

  1. Use Object.keys() to get the keys of the first object.
  2. Use Object.prototype.hasOwnProperty() to check if the second object has a key that's in the first object.
  3. Use Array.prototype.filter() to filter out keys that aren't in both objects.

Here's an example of the code:

const commonKeys = (obj1, obj2) =>
  Object.keys(obj1).filter((key) => obj2.hasOwnProperty(key));

You can test the code with this example:

commonKeys({ a: 1, b: 2 }, { a: 2, c: 1 }); // ['a']

Summary

Congratulations! You have completed the Common Keys lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like