What is the best way to combine 2 javascript objects to create a JSON structure without any nested levels?

I am having an issue with my mock server setup. I am using npm faker to generate random data, and then trying to transfer that data to another JavaScript file. My goal is to have a JSON structure like the following:

{
 0: 
     varOne: 'value'
 1:
     varTwo: 'value'
}

However, currently I am ending up with this JSON structure:

{
 file1: {
   0: 
       varOne: 'value'
   1:
       varTwo: 'value'
 },
file2: {
   0: 
       varOne: 'value'
   1:
       varTwo: 'value'
 }
}

Essentially, I have two JavaScript files that I want to combine into one without nested sub-levels in the JSON structure. The code I am using right now looks like this:

const file1 = generateFakeObject(nameOfFile1, 4)
const file2 =  generateFakeObject(nameOfFile2, 8)
data.jsonStructure = {file1, file2};

Any assistance with resolving this would be greatly appreciated!

Answer №1

The JSON structure shared in the original post does not appear to be a valid JSON format.

Are you referring to this structure?

{
    "file1": {
        "varOne": "value",
        "varTwo": "value"
    },
    "file2": {
        "varOne": "value",
        "varTwo": "value"
    }
}

If this is what you meant, check out the working demo below:

var jsonObj = {
"file1": {
"varOne": "value",
"varTwo": "value"
},
"file2": {
"varOne": "value",
"varTwo": "value"
}
};

var obj = {};

obj = {...jsonObj.file1, ...jsonObj.file2};

console.log(obj);

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

Receiving a 401 error while attempting to make an axios get request with authentication headers

I have been utilizing axios in my React project to fetch data from MongoDB. However, I am facing a challenge with the axios get requests returning a 401 error when I include my auth middleware as a parameter. This middleware mandates that the user must pos ...

What is the significance of the "@" in JXON conversion in JavaScript?

Looking at an XML structure like the one below: <calendar> <month year="2013" num="5"> <day num="1"> </month> </calendar> I decided to convert it to JSON using MDN's JXON Snippet 3. https://developer.moz ...

The JSON.stringify method is failing to correctly calculate the length of the JSON array

Hey there, I'm trying to implement an Excel upload feature that saves data into a MongoDB database. I've managed to convert the Excel cell values into JSON format and parse it successfully. However, I'm facing a challenge in determining the ...

What makes 'Parsing JSON with jQuery' unnecessary?

Just performed an ajax request with a query and noticed that my response is already in the form of a JavaScript object. When I try to parse the JSON using: var obj = jQuery.parseJSON(response); 'obj' turns out to be null, yet I can directly ac ...

Shuffling decks of cards among players at a table using JavaScript

Seems like such a simple task, but I can't seem to get it right. The idea is to have an array of 8 other arrays, each containing sets of cards (although in this case, they just have random numbers). Depending on whether passDirection is set to -1 or 1 ...

Is it possible to convert a blob to an image file using the FileReader in HTML

client side code <head> <script> var reader = new FileReader(); var objVal; var image = new Image(); reader.onload = function(e) { document.getElementById('propertyImg').setAttribute('src', e.target.result); }; fun ...

How to deserialize a JSON object containing an Interface property in a complex structure

Our team is currently developing a Web Api application using .Net 4.6. We are facing a challenge when trying to JsonConvert.DeserializeObject a complex object. This object contains a list of complex objects and within that list is an interface. For instan ...

The installation of "npm" was completed successfully, however there seems to be an issue when

I am currently facing an issue while trying to set up http-server, bower, and grunt on my Windows machine. After successfully installing them using npm install, I encountered a 'command not found' error when attempting to run the commands. Even a ...

Is it possible to store the output of every iteration in a Scenario Outline and combine all the responses into one JSON file for easy access?

I am facing an issue with saving the json response of each iteration of the Scenario Outline and merging all responses into a single json file. Unfortunately, I have not been successful in saving it in the current feature file or any other feature file. ...

"Patience is key as we await the resolution of a promise within the confines of an emitter

My goal is to wait for the promise to be resolved before continuing when the someevent event is fired. However, even though I use a then in my code snippet below, it seems that the process shuts down before the slowFunctionThatReturnsPromise is resolved, ...

What is the functionality of the arguments in the ajax function?

I'm currently following a tutorial that includes the code below: However, I'm confused about the purpose of url, cache, and success. Are they arrays? How do they function? ...

Retrieve information in JSON format using AngularJS by fetching data from SQL through PHP

My objective is to retrieve data from a mySql database using PHP, convert it to JSON, and then display it through AngularJS. Although I have successfully completed the steps leading up to this point, I am facing issues with the final step. Below are the de ...

Executing eleventy build (through npm run) within an AWS Lambda operation

I am working on an Eleventy Node project that takes JSON data and renders it as HTML. Currently, I test this locally by using npm run (which executes the eleventy CLI). Here is my envisioned workflow: Store the JSON file in an S3 bucket Automatically bu ...

Troubleshooting problems with bot roles on Discord

After spending some time coding my bot, I encountered an issue when trying to add a role to a user who didn't already have it. Everything seemed to be functioning properly until I included the member.roles.add command. Despite having every possible p ...

when cloned: running npm install results in a distinct package-lock file

I am currently running npm 5.6.0 and node v6.9.5 on OSX El Capitan 10.11.6. Situation: In my nodejs project, a package-lock.json is generated after each npm install as expected. The project, along with the package-lock.json, is saved in a repository and t ...

The absence of PHP GET variable being set

I am encountering an issue with my registration php class. It is designed to display a form and upon clicking the registration button, it triggers a function in a login javascript file. This JavaScript file utilizes ajax to send data to an index.php file. ...

What is the best approach to storing and retrieving special characters ('+<>$") from a textfield into a database using PHP?

I have a form where users can enter a personal message with a subject. The data entered in the textarea is passed to a Javascript/jQuery function, which then sends it to a PHP file for storage in a database. However, I am encountering issues when special c ...

How can I retrieve a specific key from a nested array while using ng-repeat to iterate through it

I have successfully created a code snippet that retrieves JSON data and displays it in HTML using AngularJS. <div class="activity" ng-app="stream" ng-controller="streamCtrl"> <ul ng-repeat="x in myData"> <p class="au ...

What is the best way to convert a graphql query into a JSON object?

I'm facing an issue where I need to convert a GraphQL query into a JSON object. Essentially, I have a query structured like the example below, and I'm seeking a method to obtain a JSON representation of this query. Despite my efforts in searching ...

Tips for personalizing the css styles of an alert box?

I am in need of customizing the alert box using CSS attributes. Currently, I am able to achieve a similar effect with the code below: JQUERY: $('<div class="alertMessage">Error first</div>') .insertAfter($('#componentName' ...