简体   繁体   中英

How to split array of objects by status using Handlebars.js?

I am a beginner in coding and this is a very stupid question:

I have 3 different columns with tasks: waiting / working / done

External js file with array:

var tasks = [
    {
        title: 'First Task',
        picUrl: 'imgs/test.jpg',
        status: 'pending',
    },
    {
        title: 'Second Task',
        picUrl: 'imgs/another.jpg',
        status: 'running',
    },  
];

And template:

<script type="text/x-handlebars-template" id="post-template">
    <div class="post">
        <p class="post-title">{{title}}</p>
        <img src="{{picUrl}}" alt="{{picAlt}}" class="post-Pic" />          
    </div>
</script>

How to separate them via status and put them in different columns?

You can easly create 3 news array:

var filtered_tasks = {}
for (t in tasks) {
  let task = tasks[t]
  if (!filtered_tasks[task.status]) { 
    filtered_tasks[task.status] = []
  }
  filtered_tasks[task.status].push(task)
}

Now you have :

filtered_tasks === {
  pending: [
    {
        title: 'First Task',
        picUrl: 'imgs/test.jpg',
        status: 'pending',
    }
  ],
  running : [
    {
        title: 'Second Task',
        picUrl: 'imgs/another.jpg',
        status: 'running',
    }
  ]
];

And you can do :

<div class="post">
  <h3>Running</h3>
  {{#each filtered_tasks.running}}
    <p class="post-title">{{title}}</p>
    <img src="{{picUrl}}" alt="{{picAlt}}" class="post-Pic" />   
  {{/each}} 

  <h3>Pending</h3>
  {{#each filtered_tasks.pending}}
    <p class="post-title">{{title}}</p>
    <img src="{{picUrl}}" alt="{{picAlt}}" class="post-Pic" />   
  {{/each}} 

  <h3>Done</h3>
  {{#each filtered_tasks.done}}
    <p class="post-title">{{title}}</p>
    <img src="{{picUrl}}" alt="{{picAlt}}" class="post-Pic" />   
  {{/each}}       
</div>

/!\\ Not tested code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM