Home / Uncategorized / For a given below object

For a given below object

const exampleObj = {

    taxi:

      “a car licensed to transport passengers in return for payment of a fare”,

    food: {

      sushi:

        “a traditional Japanese dish of prepared rice accompanied by seafood and vegetables”,

      apple: {

        Honeycrisp:

          “an apple cultivar developed at the MAES Horticultural Research Center”,

        Fuji:

          “an apple cultivar developed by growers at Tohoku Research Station”

      }

    }

  };

Print the above object in a nested structure and make sure the code supports deep nested structure

Below is the UI design for the give object:-


Solution: 1

const exampleObj = {
  taxi: "a car licensed to transport passengers in return for payment of a fare",
  food: {
    sushi: "a traditional Japanese dish of prepared rice accompanied by seafood and vegetables",
    apple: {
      Honeycrisp: "an apple cultivar developed at the MAES Horticultural Research Center",
      Fuji: "an apple cultivar developed by growers at Tohoku Research Station"
    }
  }
};

function printNestedObject(obj, level = 0) {
  const indent = '  '.repeat(level); // Indentation based on the current level

  for (const [key, value] of Object.entries(obj)) {
    if (typeof value === 'object' && value !== null) {
      console.log(`${indent}${key}:`);
      printNestedObject(value, level + 1); // Recursive call for nested objects
    } else {
      console.log(`${indent}${key}: ${value}`);
    }
  }
}

printNestedObject(exampleObj);

Solution: 2

const exampleObj = {
  taxi: "a car licensed to transport passengers in return for payment of a fare",
  food: {
    sushi: "a traditional Japanese dish of prepared rice accompanied by seafood and vegetables",
    apple: {
      Honeycrisp: "an apple cultivar developed at the MAES Horticultural Research Center",
      Fuji: "an apple cultivar developed by growers at Tohoku Research Station"
    }
  }
};

// Higher-order function to print nested objects
const printNestedObject = (obj, format = (key, value, indent) => `${indent}${key}: ${value}`, level = 0) => {
  const indent = '  '.repeat(level);

  // Using forEach as the higher-order function to iterate over the object entries
  Object.entries(obj).forEach(([key, value]) => {
    if (typeof value === 'object' && value !== null) {
      console.log(`${indent}${key}:`);
      printNestedObject(value, format, level + 1);  // Recursive call with incremented level
    } else {
      console.log(format(key, value, indent));  // Use the format function for the output
    }
  });
};

// Usage
printNestedObject(exampleObj);

About Sushil Kumar

Check Also

Uber NodeJS JavaScript and ReactJS interview questions answers

Deep Copy vs Shallow Copy Shallow Copy A shallow copy creates a new object with …

Leave a Reply

Your email address will not be published. Required fields are marked *