sugoke
January 26, 2016, 3:21pm
1
Hi all,
Let’s say I have the following array
“employees”:[
{“firstName”:“John”, “lastName”:“Doe”},
{“firstName”:“Anna”, “lastName”:“Smith”},
{“firstName”:“Peter”,“lastName”:“Jones”}
]
I already know how to iterate in the template which #Each .
Then let’s say I have a second collection with ages:
“ages”:[
{“firstName”:“John”, “age”: 30 },
{“firstName”:“Anna”, “age”: 30},
{“firstName”:“Peter”,“age”: 45}
]
How can I iterate the employees object, by filtering with the age from the ages collection?
Do I have to create a third one combining the 2 arrays?
Thanks
M
There are quite a few different ways you could handle this, but here’s a really quick example. Let’s say you want to filter for employees older than a specific age (and you’re linking them by first name):
test.js:
if (Meteor.isClient) {
const employees = [
{ firstName: 'John', lastName: 'Doe' },
{ firstName: 'Anna', lastName: 'Smith' },
{ firstName: 'Peter', lastName: 'Jones' }
];
const employeeAges = [
{ firstName: 'John', age: 30 },
{ firstName: 'Anna', age: 30 },
{ firstName: 'Peter', age: 45}
];
const isEmployeeOlderThan = (firstName, age) => {
return employeeAges.filter((employeeAge) => {
return ((employeeAge.firstName === firstName) && (employeeAge.age > age));
}).length > 0;
};
Template.hello.helpers({
employees() {
return employees;
},
employeesOlderThan(age) {
const filteredEmployees = [];
employees.forEach((employee) => {
if (isEmployeeOlderThan(employee.firstName, age)) {
filteredEmployees.push(employee);
}
});
return filteredEmployees;
}
});
}
test.html:
<body>
<h1>Welcome to Meteor!</h1>
{{> hello}}
</body>
<template name="hello">
<div>
Employees:
{{#each employees}}
{{firstName}}
{{/each}}
</div>
<div>
Employees Old Than 30:
{{#each employeesOlderThan 30}}
{{firstName}}
{{/each}}
</div>
</template>
sugoke
January 28, 2016, 3:07pm
3
Awesome, thanks for taking the time.