简体   繁体   中英

How to merge 2 js objects to form json structure with no sub-levels?

I have a problem in a mock server i am doing. I use npm faker to have some random data, and i go get that data to another js file. Now i want to have a json structure like this:

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

and at the moment i am getting this json structure:

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

Basically i have two js files who i want to merge in one but resulting with no sub-levels in the Json structure. At the moment my code is this:

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

Can anyone help me please???

JSON structure you provided in OP is not looks like a valid JSON.

Do you mean ?

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

If Yes, Working Demo :

 var jsonObj = { "file1": { "varOne": "value", "varTwo": "value" }, "file2": { "varOne": "value", "varTwo": "value" } }; var obj = {}; obj = {...jsonObj.file1, ...jsonObj.file2}; console.log(obj); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM