简体   繁体   中英

Creating a double nested JSON object

So I have three tables and the structure that I want to create is:

{
   'Id'
   'Name'
   'ImagePath'
   'SubCategory':[{

              'Id'
              'Name'
              'ImagePath'
              'Dishes': [{

                      'Id'
                      'Name'
                      'ImagePath'
               }, More Dish Objects]
   }, More SubCategory Objects ]

} 

I'm querying this data from a MySQL Database and so far I think I've got the query right:

Select subcategory.*, dishes.*, category.* from category 
LEFT JOIN subcategory on subcategory.cat_id = category.id 
LEFT JOIN dishes on dishes.subcat_id = subcategory.id;

Now I just can't wrap my head around how to structure this using JavaScript.

This is how you would create a JSON object matching the one you gave in javascript

var myJSON ={
    'Id':'sampleId',
    'Name':'sampleName',
    'ImagePath':'sampleImagePath',
    'SubCategory':{
        'Id':'subCategoryId',
        'Name':'subCategoryName',
        'ImagePath':'subCategoryImagePath',
        'Dishes':{
            'Id':'dishesId',
            'Name':'dishesName',
            'ImagePath':'dishesImagePath'
        }
    'AnotherSubCategoryObject':'data'
    }
}

//calling ImagePath in javascript. Value is sampleImagePath
var imagePathValue=myJSON.ImagePath;

//calling subCategoryImagePath. Value is subCategoryImagePath
var subCategoryImagePath = myJSON.SubCategory.ImagePath;

//calling Dishes Name. Value is dishesName
var dishesName = myJSON.SubCategory.Dishes.Name;

//assinging values to subCategoryName

myJSON.SubCategory.Name='anotherValue';

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