Search This Blog

2017/12/30

Node.js looping through 2-dimensional jagged array

consider following jagged array structure which is place holder for routing data collected to to organize express routing details

var sample = {
    'get': [
        ['api/spaceships', 'get all'],
        ['api/spaceships/:id', 'get filtered list']
    ],
    'post': [
        ['api/spaceships', 'get all'],
        ['api/spaceships/:id', 'get filtered list']
    ]
}

javascript code below will loop through and print values

Code:
    console.log('-------------------------------------------------');
    for (var j = 0; j < Object.keys(sample).length; j++) {
        console.log('HTTP Method :' + Object.keys(sample)[j]);
        for (var i = 0; i < sample[Object.keys(sample)[j]].length; i++) {
        console.log('-----------Route--------------------');
        console.log('Key:' + sample[Object.keys(sample)[j]][i][0]);
        console.log('Value:' + sample[Object.keys(sample)[j]][i][1]);
        console.log('-----------Route--------------------');
        }
        console.log('-----------Next Iteration---------------------');
    }


Output:

    -------------------------------------------------
    HTTP Method :get
    -----------Route--------------------
    Key:api/spaceships
    Value:get all
    -----------Route--------------------
    -----------Route--------------------
    Key:api/spaceships/:id
    Value:get filtered list
    -----------Route--------------------
    -----------Next Iteration---------------------
    HTTP Method :post
    -----------Route--------------------
    Key:api/spaceships
    Value:get all
    -----------Route--------------------
    -----------Route--------------------
    Key:api/spaceships/:id
    Value:get filtered list
    -----------Route--------------------
    -----------Next Iteration---------------------

No comments:

Post a Comment