Search code examples
javascriptarraysjsonjson2html

json2html - Create inline function for JSON data in array w/ multiple elements


I have the following JSON data:

{"orders":[
{"id":16,"status":"completed","total":"45.00"},
{"id":17,"status":"completed","total":"55.00"}
]}

how do I transform this data to html using json2html? ${orders.0.total} works but I want it to transform all orders, not just array 0.

I have tried the solution from this answer, but it won't work.

This is what I have:

<body>
    <ul id="list"></ul>
</body>

<script type="text/javascript">
    //List items
    var myjson = [{"orders":[
                 {"id":16,"status":"completed","total":"45.00"},
                 {"id":17,"status":"completed","total":"55.00"}
                 ]}];

    //List item transform
    var orderTransform = {"tag":"div","html":"${total}"}

    var transform = {"tag":"div","children":function(){
        return( json2html.transform(this,orderTransform) );
    }};

    $(function(){
        //Create the list
        $('#list').json2html(myjson,transform);
    });
</script>

thx


Solution

  • Your transform should be modified to:

    var transform = {"tag":"div","children":function(){
            return( json2html.transform(this.orders,orderTransform) );
    }};
    

    Note the change of this to this.orders, as the root transform references the {orders: [...]} object, so in the children function it is necesary to specify the new array that is being used as the data.

    The original code passed this as the data for the children which would make json2html try to rerender the {orders: [...]} object using the orderTransform, which is incorrect, so instead it is important to explicitly specify that the data for that transform is in the orders field.