(Beginner)
Please consider the below code; is my following understanding correct?
I would greatly appreciate any feedback.
Best regards
- 'fruits’ is an array-like object that contains ‘keys’ and ‘values’
- keys are like labels and are separated from their value counterparts using a colon ‘:’
- in my example, the primary keys of fruits are ‘level_0’ and ‘level_1’
- each of the keys contains two subkeys namely ‘column_1’ and ‘column_2’
1. const body = [];
2. const fruits = {
3. level_0:{ column_1 : { fruit : 'apple' }, column_2 : { fruit : 'banana' }, },
4. level_1:{ column_1 : { fruit : 'cherry' }, column_2 : { fruit : 'date' }, },
5. }; // Close fruits
Continuing, the following code builds on ‘fruits’:
- the ‘for’ loop counts the number of ‘primary’ keys
- the ‘if’ condition filters the keys ‘level_0’ and ‘level_1’ using boolean evaluation
- ‘header’ will be assigned name ‘level_0’ on first iteration and ‘level_1’ on second
- create an empty array called ‘row’ that is recreated on each iteration
On the first iteration:
- add the value of ‘level_0’ / ‘column_1’ to the array ‘row’ (apple)
- append the value of ‘level_0’ / ‘column_2’ to the array ‘row’ (banana)
- add the row array to the body array
On the second iteration:
- add the value of ‘level_1’ / ‘column_1’ to the array ‘row’ (cherry)
- append the value of ‘level_1’ / ‘column_2’ to the array ‘row’ (date)
- append the row array to the body array
7. for (let keys in fruits) {
8. if(fruits.hasOwnProperty(keys)) {
9. let header = fruits[keys];
10. let row = new Array();
11. row.push( header.column_1 );
12. row.push( header.column_2 );
13. body.push(row);
14. } // Close IF
15. } // Close FOR
