2016-05-16 4 views
0

У меня есть вложенный объект JSON, я должен пройти через все уровни и получить свойства + имя объекта,Уплотненный JSON к плоскому HTML таблицы

Это то, что я ожидал,

MainObject.Property1 
MainObject.Property2 
MainObject.Property3 
ChildObject1.Property1 
ChildObject1.PropertyN 
ChildsChildObject1.Property1 
ChildsChildObject1.PropertyN 
.. so on.. 

Я очень новый JavaScript, так останься со мной, я попытался это, но не работает,

walker(mainObject); 

    function walker(object) { 
     displayAllProperties(object); 
     digThroughAllObjects(object); 
    } 

    function displayAllProperties(object) { 
     for (var property in object) { 
      var type = typeof object[property]; 
      if (type === 'string' || type === 'number' || type === 'boolean' || object[property] instanceof Date || !object[property]) { 
       console.log(object + " " + property); 
      } 
     } 
    } 

    function digThroughAllObjects(object) { 
     for (var property in object) { 
      if (typeof property === "object") { 
       walker(property); 
      } 
     } 
    } 

Update

Я применил предложение к моему коду, и оно немного улучшилось.

Вы можете использовать JSON, но для меня мой код должен работать с любым JSON ..

JSON example

Update 2

Новейший код не работает,

function displayAllProperties(object) { 
    for (var property in object) { 
    var type = typeof object[property]; 
    if (type === 'string' || type === 'number' || type === 'boolean' || object[property] instanceof Date || !object[property]) { 
     console.log(object + " " + property); 
    } else if (type === "object") { 
     displayAllProperties(object[property]); 
    } 
    } 
} 

Обновление 3

Я получаю ответ JSON в иерархическом дереве, но мне нужно создать плоскую динамическую таблицу, поэтому моя первая задача - получить все имена свойств, чтобы я мог создать массив имен столбцов и использовать его для создания динамической таблицы.

+0

могли бы вы предоставить образец JSON? –

+0

Duplicate of many, many JSON traversers – mplungjan

+0

Вы переходите из 'item' в' value'. Кроме этого, код выглядит нормально. –

ответ

2

Посмотрите на JavaScript консоли браузера должно быть сообщение об ошибке говорит вам точную проблему

function walker(item) { 
    display(item); 

    if (typeof value === "object") { <-- value is not defined 
     $.each(value, walker); 
    } 
} 
+0

Спасибо @epascarello, я применил ваше предложение, но это не помогло с конечным результатом, я хочу, +1 для начальной справки – Change

+0

Ну, чтобы получить конечный результат, вам нужно построить строка с родительскими ключами. Все, что вы делаете, это выписать текущий ключ. – epascarello

0

Это, кажется, что вы хотите:

mainObject = {"odata.metadata":"http://services.odata.org/V3/OData/OData.svc/$metadata#Categories","value":[{"Products":[{"Supplier":{"ID":1,"Name":"Tokyo Traders","Address":{"Street":"NE 40th","City":"Redmond","State":"WA","ZipCode":"98052","Country":"USA"},"Location":{"type":"Point","coordinates":[-122.107711791992,47.6472206115723],"crs":{"type":"name","properties":{"name":"EPSG:4326"}}},"Concurrency":0},"ProductDetail":null,"ID":0,"Name":"Bread","Description":"Whole grain bread","ReleaseDate":"1992-01-01T00:00:00","DiscontinuedDate":null,"Rating":4,"Price":2.5},{"Supplier":{"ID":0,"Name":"Exotic Liquids","Address":{"Street":"NE 228th","City":"Sammamish","State":"WA","ZipCode":"98074","Country":"USA"},"Location":{"type":"Point","coordinates":[-122.03547668457,47.6316604614258],"crs":{"type":"name","properties":{"name":"EPSG:4326"}}},"Concurrency":0},"ProductDetail":{"ProductID":1,"Details":"Details of product 1"},"ID":1,"Name":"Milk","Description":"Low fat milk","ReleaseDate":"1995-10-01T00:00:00","DiscontinuedDate":null,"Rating":3,"Price":3.5}],"ID":0,"Name":"Food"},{"Products":[{"Supplier":{"ID":0,"Name":"Exotic Liquids","Address":{"Street":"NE 228th","City":"Sammamish","State":"WA","ZipCode":"98074","Country":"USA"},"Location":{"type":"Point","coordinates":[-122.03547668457,47.6316604614258],"crs":{"type":"name","properties":{"name":"EPSG:4326"}}},"Concurrency":0},"ProductDetail":{"ProductID":1,"Details":"Details of product 1"},"ID":1,"Name":"Milk","Description":"Low fat milk","ReleaseDate":"1995-10-01T00:00:00","DiscontinuedDate":null,"Rating":3,"Price":3.5},{"Supplier":{"ID":0,"Name":"Exotic Liquids","Address":{"Street":"NE 228th","City":"Sammamish","State":"WA","ZipCode":"98074","Country":"USA"},"Location":{"type":"Point","coordinates":[-122.03547668457,47.6316604614258],"crs":{"type":"name","properties":{"name":"EPSG:4326"}}},"Concurrency":0},"ProductDetail":null,"ID":2,"Name":"Vint soda","Description":"Americana Variety - Mix of 6 flavors","ReleaseDate":"2000-10-01T00:00:00","DiscontinuedDate":null,"Rating":3,"Price":20.9},{"Supplier":{"ID":0,"Name":"Exotic Liquids","Address":{"Street":"NE 228th","City":"Sammamish","State":"WA","ZipCode":"98074","Country":"USA"},"Location":{"type":"Point","coordinates":[-122.03547668457,47.6316604614258],"crs":{"type":"name","properties":{"name":"EPSG:4326"}}},"Concurrency":0},"ProductDetail":{"ProductID":3,"Details":"Details of product 3"},"ID":3,"Name":"Havina Cola","Description":"The Original Key Lime Cola","ReleaseDate":"2005-10-01T00:00:00","DiscontinuedDate":"2006-10-01T00:00:00","Rating":3,"Price":19.9},{"Supplier":{"ID":0,"Name":"Exotic Liquids","Address":{"Street":"NE 228th","City":"Sammamish","State":"WA","ZipCode":"98074","Country":"USA"},"Location":{"type":"Point","coordinates":[-122.03547668457,47.6316604614258],"crs":{"type":"name","properties":{"name":"EPSG:4326"}}},"Concurrency":0},"ProductDetail":{"ProductID":4,"Details":"Details of product 4"},"ID":4,"Name":"Fruit Punch","Description":"Mango flavor, 8.3 Ounce Cans (Pack of 24)","ReleaseDate":"2003-01-05T00:00:00","DiscontinuedDate":null,"Rating":3,"Price":22.99},{"Supplier":{"ID":0,"Name":"Exotic Liquids","Address":{"Street":"NE 228th","City":"Sammamish","State":"WA","ZipCode":"98074","Country":"USA"},"Location":{"type":"Point","coordinates":[-122.03547668457,47.6316604614258],"crs":{"type":"name","properties":{"name":"EPSG:4326"}}},"Concurrency":0},"ProductDetail":null,"ID":5,"Name":"Cranberry Juice","Description":"16-Ounce Plastic Bottles (Pack of 12)","ReleaseDate":"2006-08-04T00:00:00","DiscontinuedDate":null,"Rating":3,"Price":22.8},{"Supplier":{"ID":0,"Name":"Exotic Liquids","Address":{"Street":"NE 228th","City":"Sammamish","State":"WA","ZipCode":"98074","Country":"USA"},"Location":{"type":"Point","coordinates":[-122.03547668457,47.6316604614258],"crs":{"type":"name","properties":{"name":"EPSG:4326"}}},"Concurrency":0},"ProductDetail":null,"ID":6,"Name":"Pink Lemonade","Description":"36 Ounce Cans (Pack of 3)","ReleaseDate":"2006-11-05T00:00:00","DiscontinuedDate":null,"Rating":3,"Price":18.8},{"odata.type":"ODataDemo.FeaturedProduct","Supplier":null,"ProductDetail":null,"ID":9,"Name":"Lemonade","Description":"Classic, refreshing lemonade (Single bottle)","ReleaseDate":"1970-01-01T00:00:00","DiscontinuedDate":null,"Rating":7,"Price":1.01},{"odata.type":"ODataDemo.FeaturedProduct","Supplier":null,"ProductDetail":null,"ID":10,"Name":"Coffee","Description":"Bulk size can of instant coffee","ReleaseDate":"1982-12-31T00:00:00","DiscontinuedDate":null,"Rating":1,"Price":6.99}],"ID":1,"Name":"Beverages"},{"Products":[{"Supplier":{"ID":1,"Name":"Tokyo Traders","Address":{"Street":"NE 40th","City":"Redmond","State":"WA","ZipCode":"98052","Country":"USA"},"Location":{"type":"Point","coordinates":[-122.107711791992,47.6472206115723],"crs":{"type":"name","properties":{"name":"EPSG:4326"}}},"Concurrency":0},"ProductDetail":null,"ID":7,"Name":"DVD Player","Description":"1080P Upconversion DVD Player","ReleaseDate":"2006-11-15T00:00:00","DiscontinuedDate":null,"Rating":5,"Price":35.88},{"Supplier":{"ID":1,"Name":"Tokyo Traders","Address":{"Street":"NE 40th","City":"Redmond","State":"WA","ZipCode":"98052","Country":"USA"},"Location":{"type":"Point","coordinates":[-122.107711791992,47.6472206115723],"crs":{"type":"name","properties":{"name":"EPSG:4326"}}},"Concurrency":0},"ProductDetail":{"ProductID":8,"Details":"Details of product 8"},"ID":8,"Name":"LCD HDTV","Description":"42 inch 1080p LCD with Built-in Blu-ray Disc Player","ReleaseDate":"2008-05-08T00:00:00","DiscontinuedDate":null,"Rating":3,"Price":1088.8}],"ID":2,"Name":"Electronics"}]} 
 

 
function displayAllProperties(object) { 
 
    var parentObj = ""; 
 
    for (var property in object) { 
 
    var type = typeof object[property]; 
 
    if (type === 'string' || type === 'number' || type === 'boolean' || object[property] instanceof Date || !object[property]) { 
 
     console.log((parentObj?parentObj+".":"")+property+":"+object[property]); 
 
    } else if (type === "object") { 
 
     parentObj = property; 
 
     displayAllProperties(object[property]); 
 
    } 
 
    } 
 
} 
 
displayAllProperties(mainObject)

Смежные вопросы