How can I quickly duplicate the design of a JSON Object?

Perhaps the title is a bit basic. Essentially, I am looking for something similar to mysqldump ... --no-data .... For instance, I have a JSON object structured like this:

{ "key1" : "value1",
  "key2" : "value2",
  "key3" : {
      "key3a" : 1,
      "key3b" : 2
  },
  "key4" : "value3"
}

What I am aiming for is an empty object with the identical structure, such as:

{ "key1" : null,
  "key2" : null,
  "key3" : {
      "key3a" : null,
      "key3b" : null
  },
  "key4" : null
}

Answer №1

If you're looking for a way to create a deep copy of an object but return null for non-object values, you're essentially trying to perform a form of "deep cloning". One way to achieve this is by using a recursive function:

function deepAutumnClone(obj){
  if (typeof obj !== 'object') return null;
  var clone = {};
  for (var key in obj) {
    clone[key] = deepAutumnClone(obj[key]);
  }
  return clone;
}

To use the function, you would call it like this:

var originalObj = { "key1" : "value1",
  "key2" : "value2",
  "key3" : {
      "key3a" : 1,
      "key3b" : 2
  },
  "key4" : "value3"
};
console.log(deepAutumnClone(originalObj));

Keep in mind that the function may need adjustments depending on how you want to handle arrays or other non-object values.

Lastly, it's worth noting that the term "JSON object" is a misnomer in this case, as JSON refers to a text-based data interchange format, whereas what you have here is a standard JavaScript object.

Answer №2

Here is a unique function that supports resetting Arrays as well as Objects without setting inherited properties to null:

function duplicateAndReset(input) {

    var result = null;

    if (input instanceof Array) {
        result = [];
        for (var index = 0; index < input.length; index++) {
                result[index] = duplicateAndReset(input[index]);
        }
        return result;
    }

    if (input instanceof Object) {
        result = {};
        for (property in input) {
            if (input.hasOwnProperty(property)) {                            
                result[property] = duplicateAndReset(input[property]);
            } 
        }
    } 

    return result;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve and save only the outcome of a promise returned by an asynchronous function

I am currently working on an encryption function and have encountered an issue where the result is returned as an object called Promise with attributes like PromiseState and PromiseResult. I would like to simply extract the value from PromiseResult and s ...

Conflicting issues with jQuery's load() method

I am facing an issue with loading two HTML pages into a single div. I have index.html and try.html in the root folder, where try.html is loaded into index.html's div (#content) when Button 01 is clicked on index.html. The problem arises when I further ...

How to retrieve information from JSON files utilizing arrays

I have a JSON object that contains connection points data in an array. Here is an example of the structure: assetType : "this" connectionPoints:Array(1) type:{name: "Structure", In my TypeScript file, I am handling this data like so (entity represents ...

Combining the results of JSON data into a single output

I am working with PHP and have a JSON output that looks like this: [{"Title":"Message","count":"180","Number":"200"}, {"Title":"Message","count":"200","Number":"400"}] Is there a way to combine the counts and numbers to get the following result? [{"Tit ...

Ways to split an object into DTO and BO

Recently, I've been dealing with an old object that contains both data and behavior. To make things more efficient, I've decided to serialize this object using JSON so it can be stored in a file and shared between users. However, I now realize t ...

Struggling to display the Three.js LightMap?

I'm having trouble getting the lightMap to show on my mesh. Here's the code I'm using: loader.load('model.ctm', function (geometry) { var lm = THREE.ImageUtils.loadTexture('lm.jpg'); var m = THREE.ImageUtils.loadT ...

What are the methods for choosing various boxes using the UP/DOWN/RIGHT/LEFT arrow keys?

This code snippet displays a 3x3 matrix where boxes can be hovered over and selected. The goal is to navigate around with keys and select boxes using ENTER. Can anyone provide guidance on how to achieve this functionality? <link rel="stylesheet" href ...

What is the best way to incorporate the :after pseudo-element in JavaScript code

HTML: This is my current code snippet <div class="one"> Apple </div> I am looking to dynamically add the word "juice" using JavaScript with the .style property. Is there an equivalent of :: after in CSS, where I can set the content in JavaS ...

Covering a doughnut shape with a twisting spiral

I want to achieve a hula hoop covered in tape effect using three.js. The 3D model should look similar to the image below. https://i.sstatic.net/lj9cR.jpg I have been able to create the hoop in 3D space using TorusGeometry and pan around, but I am strugg ...

Logging in using Selenium WebDriver in Java

I'm just starting out with selenium webdriver and I need to automate a webpage for my project. Right now, I'm working on the login page but I'm having trouble with the login button. I'm not sure which locator to use for it. The login bu ...

Generating a JSON file using JavaScript amidst the presence of unconventional characters in JSON keys

In my Node Red Function Node, I'm currently facing a challenge of generating a JSON file from JavaScript code. The specific format I need for the JSON file is as follows: [ { "H-Nr.":"1", "Pos.-Nr.":"1" }, { "H-Nr.":"1", ...

Strange behavior occurs when a DOCTYPE is specified in XSLT and javascript interactions

Within our XLST, we utilize "vanilla" JavaScript to manipulate certain div elements within our reports. One particular div sits in the center of the screen and overlaps all other content. The code snippet below is used to position this div when the page lo ...

Using JavaScript to create a dynamic to-do list that persists on the browser even when refreshed

I created a Javascript Todolist that is functioning well, but I am seeking a way to ensure that my Todo-items persist on the browser even after refreshing until I choose to delete them. Any suggestions or advice on how I can achieve this? ...

Unable to display results in React Native due to FlatList not being shown

I'm a beginner to React Native and I'm attempting to create a simple flatlist populated from an API at , but unfortunately, no results are displaying. Here's my App.tsx code: import React from 'react'; import type {PropsWithChildre ...

Creating a dependent picklist feature using node.js and express

I am currently delving into the world of node.js and express. In my node.js application, I am utilizing express along with express-handlebars as the templating framework. My goal is to incorporate a dependent picklist that dynamically renders based on the ...

Can you explain the varying methods of importing material-ui components and how they differ from each other?

After delving into the documentation for material-ui and exploring various online resources, it appears that there are multiple methods for importing the same component: import TextField from 'material-ui/TextField'; // or import TextField from ...

Error: The property 'classList' of null is unreachable for HTMLImageElement

I'm facing an issue on my website that's causing the following error message to pop up: Uncaught TypeError: Cannot read property 'classList' of null at HTMLImageElement. Here's the code I've been using: https://jsfiddle. ...

zingcharts with multiple lines on x axis representing time

I am facing a rather interesting challenge with plotting data. I want to create a chart where time is the x-axis scale and multiple lines are plotted, each with varying time intervals between data points. While zingcharts has provided documentation on gene ...

The term "Cardlist" has not been defined and is therefore causing an

I created a CardList and attempted to add cards into the list using map, but encountered an error import React from 'react'; import Card from './Card'; const CardsContainer = ({robots}) => { const cardComponents = robots.map((r ...

What method can I use to identify the most widely-used edition of a specific npm module?

While the npm registry does provide metrics on the most depended packages, have you ever wondered if it's possible to determine the most popular version of a specific package? For example, as a user considering upgrading to react-router^4.0.0, wouldn ...