1. function mirrorJson(jsonData, path = [], prefix = "") {
  2. // Validate input
  3. if (typeof jsonData !== 'object' || jsonData === null) {
  4. console.error("Invalid input: jsonData must be an object.");
  5. return;
  6. }
  7. // Log the current path
  8. console.log(`Mirroring at path: ${path.join('.')}, Prefix: ${prefix}`);
  9. const mirroredData = {};
  10. for (const key in jsonData) {
  11. if (jsonData.hasOwnProperty(key)) {
  12. const currentPath = [...path, key]; // Create a new path array
  13. const value = jsonData[key];
  14. if (typeof value === 'object' && value !== null) {
  15. // Recursive call for nested objects/arrays
  16. mirrorJson(value, currentPath, prefix ? `${prefix}.${key}` : key);
  17. } else {
  18. // Assign the value to the mirrored data
  19. mirroredData[prefix ? `${prefix}.${key}` : key] = value;
  20. }
  21. }
  22. }
  23. return mirroredData;
  24. }
  25. // Example usage (for manual execution)
  26. // const originalJson = {
  27. // "name": "John Doe",
  28. // "age": 30,
  29. // "address": {
  30. // "street": "123 Main St",
  31. // "city": "Anytown"
  32. // },
  33. // "hobbies": ["reading", "hiking"]
  34. // };
  35. // const mirroredJson = mirrorJson(originalJson);
  36. // console.log(JSON.stringify(mirroredJson, null, 2));

Add your comment