Get value for key from nested JSON object in JavaScript


In the given problem statement we are asked to get value for key from nested JSON object with the help of javascript functionalities. In Javascript we can solve and access the json data object with the help of dot notation or bracket notation.

Before starting coding for the given problem, let's understand what exactly is the JSON object:

What is JSON and nested JSON objects?

JSON’s full form is Javascript Object Notation. It is a standard text based format to show the structured data. It is basically used to transmit data in web applications, which means we can send data to the server and the server can send back data in JSON format.

Nested JSON object means the objects present in a JSON file can be nested inside other objects. And the same field name can also be in a nested object. But every nested object should have a unique path.

{
    "name": "Super Hero",
    "homeTown": "Metro City",
    "birthYear": 2000,
    "active": true,
    "members": [
      {
        "name": "Molecule Man",
        "age": 29,
        "powers": ["Radiation resistance", "Turning tiny", "Radiation blast"]
      },
      {
        "name": "Madame Uppercut",
        "age": 39,
        "powers": [ "Million tonne punch", "Damage resistance"]
      },
}

Logic for The Above Problem

The easiest way to access the value for key from nested JSON object in Javascript with the help of dot notation and bracket notation.

So at first glance, we will use a nested JSON data structure to access its keys. There are two ways to access the object keys: first is dot notation and second is bracket notation. And we can also create a function to access the keys.

Below are algorithm and code to access the keys of nested JSON object with and without function:

Algorithm − Without function

step 1: Declare a Json object and name it data. This data contains objects like name, age, address. And address has nested properties like street, city and state.

Step 2: Now we will access the name and street from the above defined data. So here we will use dot notation to access it and print on the console.

Step 3: After accessing the name and street address with dot notation, now we will access the age and state properties with the help of bracket notation. And show the output on the console.

Example

// Example JSON object
const data = {
  "name": "John",
  "age": 30,
  "address": {
    "street": "123 Main St",
    "city": "Anytown",
    "state": "CA"
  }
};
// Accessing nested properties with dot notation
const name = data.name;
const street = data.address.street;
console.log("My name is: " + name + ", Street address is: " + street);
// Accessing nested properties with bracket notation
const age = data["age"];
const state = data["address"]["state"];
console.log("My age is: " + age + ", State is: " + state);

Output

My name is: John, Street address is: 123 Main St
My age is: 30, State is: CA

Algorithm − With function

Step 1: Declare a Json object called data. This data contains properties like name, age, address. And address has three nested objects like street, city and state.

Step 2: After creating the nested JSON objects, we will define a function called getNestedKeys to access the nested keys of the JSON data. Inside this function we have initiated an if condition, which is checking that the key is directly available in the json data or not, if the condition is true the return its value.

Step 3: If data is not present directly and data is nested then we will define a variable named keys which is representing nested data with dot.

Step 4: Define another variable called value which is holding json data called obj. And initialize a for loop which will run until the length of keys. And find out the nested key value pair. If data is found then return it otherwise return undefined.

Step 5: So this is how the above function will work. And now call the created function and print the values of nested keys.

Example 

// Example JSON object
  const data = {
    "name": "John",
    "age": 30,
    "address": {
      "street": "421 Main Street",
      "city": "Anytown",
      "state": "CA"
    }
  };
// function to access the nested properties
function getNestedKeys(obj, key) {
    if (key in obj) { 
      return obj[key];
    }
    const keys = key.split("."); 
    let value = obj; 
    for (let i = 0; i < keys.length; i++) {
      value = value[keys[i]];
      if (value === undefined) {
        break;
      }
    }
   
    return value;
  } 
  // Using the getNestedKeys method to get a value for a key
  const name = getNestedKeys(data, "name");
  const age = getNestedKeys(data, "age");
  const street = getNestedKeys(data, "address.street");
  const state = getNestedKeys(data, "address.state");
  console.log("Name: ", name);
  console.log("Age: ", age);
  console.log("Street: ",street);
  console.log("State: ",state);

Output

Name:  John
Age:   30
Street:  421 Main Street
State:  CA

Complexity

The time complexity for the above algorithms, which is using dot notation and bracket notation, is O(1) on average. This is because we are accessing an object property using only one notation either dot or bracket notation, which involves a direct lookup of the object in a hash table. So the hash table has a constant time complexity. While the function algorithm uses O(n) time to execute the function, where n is the number of properties in a JSON object. As the function needs to traverse every object to find the keys. And space complexity for this method is also O(n). Because it is a recursive call which adds a new call frame to the stack.

Conclusion

In this code we have implemented different ways of accessing the key values and also used a function to access the keys. In the above algorithms we are accessing nested properties in a JavaScript object which is a fast and efficient method with a constant time complexity. Because of dot and bracket notation. These notations are widely used to access the JSON keys.

Updated on: 23-Aug-2023

13K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements