创建双嵌套JSON对象

时间:2018-02-06 23:05:52

标签: javascript json javascript-objects

所以我有三个表,我想要创建的结构是:

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

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

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

} 

我从MySQL数据库查询这些数据,到目前为止我认为我的查询正确:

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

现在我无法围绕如何使用JavaScript来构建它。

1 个答案:

答案 0 :(得分:0)

这是如何创建一个与您在javascript中提供的JSON对象相匹配的JSON对象

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';