Search code examples
jsonextjsjsonstore

How to load json store with multiple root elements?


In one of my projects I need to load the Json store with a JSOn server response as follows. In the JSon response i am getting 2-3 root elements. but in the store configuration i can only provide 1 root element.

{
    {"level2List":[{id:'id1', name:'sample'},....]},
    {"level3List":[{id:'id1', name:'sample'},....]},
    {"level4List":[{id:'id1', name:'sample'},....]}
}

my store config is like below.

store = new Ext.data.JsonStore({
// store configs
storeId: 'myStore',
proxy: {
    type: 'ajax',
    url: 'xml/getKpiInputData.json',
    reader: {
        type: 'json',
        root: 'level3List',
        idProperty: 'name'
    }
},
fields: [
        {name: 'name'},
        {name: 'id'},
       ...
    ],
remoteFilter: false,
remoteSort: true,
    pageSize: 10,
autoLoad: {start: 0, limit: 10}
 });

If i give the 1 root element(for ex. level3List) it is loading the respective items properly. But I need the solution to load data from multiple root elements. Please help me in loading the data to the store.


Solution

  • If you're using 4.x, the root parameter can be a function:

    Ext.define('MyModel', {
        extend: 'Ext.data.Model',
        fields: ['name']
    });
    
    Ext.require('*');
    
    Ext.onReady(function(){
    
        var store = new Ext.data.Store({
            model: MyModel,
            proxy: {
                type: 'memory',
                reader: {
                    type: 'json',
                    root: function(o){
                        var out = [];
                        return out.concat(o.root1, o.root2, o.root3);
                    }
                }
            },
            data: {
                root1: [{
                    name: 'Item 1'
                }],
                root2: [{
                    name: 'Item 2'
                }],
                root3: [{
                    name: 'Item 3'
                }]
            }
        });
    
        store.load();
        console.log(store.getCount());
    });