If you have two sets of data and one set is referencing the other set, you will need to do a "double loop" to iterating through the data. But, there is a way to eliminate one loop and shorten the code.
For example, set 1 is the list of employees and set 2 is the list of working shift.
If you are using FOR loop, your codes will look similar to the following:
var employees = [];
employees.push({name: 'Mike', shift_id:'A'});
employees.push({name: 'Micky', shift_id:'B'});
employees.push({name: 'Mini', shift_id:'C'});
var shifts = [];
shifts.push({id: 'A', start_time: '08:00', end_time: '17:00'});
shifts.push({id: 'B', start_time: '09:00', end_time: '18:00'});
var s;
for (var i = 0; i < employees.length; i++) {
s = null;
// look for the shift:
for (var j = 0; j < shifts.length; j++) {
if (shifts[j].id == employees[i].shift_id) {
s = shifts[j];
break;
}
}
if (s != null){
console.log(employees[i].name, s.start_time);
} else {
console.log(employees[i].name, 'Cannot find the shift record');
}
}
The JavaScript object is a key value collection:
o = {};
o['a'] = 'Apple';
o['b'] = 'Banana';
And you can access the value:
console.log(o['b']);
Below is the code that uses the key value collection to store the shift information and it will save us from writing one FOR loop.
var employees = [];
employees.push({name: 'Mike', shift_id:'A'});
employees.push({name: 'Micky', shift_id:'B'});
employees.push({name: 'Mini', shift_id:'C'});
var shifts = {};
shifts['A'] = {id: 'A', start_time: '08:00', end_time: '17:00'};
shifts['B'] = {id: 'B', start_time: '09:00', end_time: '18:00'};
var s;
for (var i = 0; i < employees.length; i++) {
s = null;
// look for the shift:
if (shifts.hasOwnProperty(employees[i].shift_id)) {
s = shifts[employees[i].shift_id];
console.log(employees[i].name, s.start_time);
} else {
console.log(employees[i].name, 'Cannot find the shift record');
}
}
Subscribe to:
Post Comments (Atom)
We are moving
We are moving this blog to our new blog site: https://ciysys.com/blog/nodejs.htm
-
Overview Usually, we start developing a new system with designing database and then writing codes. If you are not a fan of ORM, you will h...
-
Below is the sample HTML which will hide the URL at the page header when printing with Javascript. <html moznomarginboxes > ...
-
You can draw a simple pie chart & doughnut chart with SVG + CSS. This is quite simple and straight forward. But the limitation is that i...
No comments:
Post a Comment