Search code examples
javascripthtmljsonaurelia

Displaying the Json result in Table with some logic


i have an requirement to display some Json data in Html table using Auralia js.

Hear is my Json data

[{
    "Key": "Name",
    "value": "Sriram",
    "order": "01"
  }, {
    "Key": "Email",
    "value": "sriram@gmail",
    "order": "02"
  }, {
    "Key": "Genader",
    "value": "male",
    "order": "03"
  }, {
    "Key": "DOB",
    "value": "01-01-88",
    "order": "04"
  }, {
    "Key": "MobileNo",
    "value": "999999999",
    "order": "05"
  }, "Key": "Address", "value": "", "order": "06"
}]

Now i need to show this table where all "order" evens at one side and odds at other side

enter image description here

Is there any simple way to achive this in using Aurelia js/JavaScript

Thanks


Solution

  • The correct way to accomplish this goal in Aurelia is to use a Value Converter to filter the collection. You could create a single value converter that can do both odds and evens, but I think the code is more readable by creating two value converters. I've modified @LStarky's solution to show how to do this:

    Runable gist: https://gist.run?id=1a66d5495314b06e378062610bd8da80**

    app.html

    <template>
      <div class="container-fluid">
      <div class="container-fluid">
        <h1>Bootstrap Method (Responsive)</h1>
        <p><i>The second column will wrap down below on smaller screens... 
        if you see it in one column, try widening the screen</i></p>
        <div class="row">
          <div class="col-xs-6">
            <div repeat.for="field of myData | odds">
              <p><b>${field.Key}:</b> ${field.value}</p>
            </div>
          </div>
          <div class="col-xs-6">
            <div repeat.for="field of myData | evens">
              <p><b>${field.Key}:</b> ${field.value}</p>
            </div>
          </td>
        </div>
      </div>
    </template>
    

    app.js

    export class App {
      myData = [{
          "Key": "Name",
          "value": "Sriram",
          "order": "01"
        }, {
          "Key": "Email",
          "value": "sriram@gmail",
          "order": "02"
        }, {
          "Key": "Genader",
          "value": "male",
          "order": "03"
        }, {
          "Key": "DOB",
          "value": "01-01-88",
          "order": "04"
        }, {
          "Key": "MobileNo",
          "value": "999999999",
          "order": "05"
        }, "Key": "Address", "value": "", "order": "06"
      }];
    }
    
    export class EvensValueConverter {
      toView(value) {
        return value.filter( x => parseInt(x.order) % 2 === 0 );
      }
    }
    
    export class OddsValueConverter {
      toView(value) {
        return value.filter( x => parseInt(x.order) % 2 === 1 );
      }
    }