RuNpiXelruN RuNpiXelruN - 24 days ago 5
Javascript Question

Functional Javascript: Having trouble iterating through an object that has nested objects and arrays

I'm having difficulty trying to access my data in a table structured as below. I want a clean and efficient way of accessing my nested data through a functional Javascript approach. If anyone can show how this can be done functionally using Ramda or plain ES6 it'd be much appreciated! Please see the example table structure below.




let tables = {
table1: {
headings: [ 'hey', 'there' ],
rows: [ 'row 1 here', 'row 2 here' ],
},
table2: {
headings: [ 'sup', 'yall' ],
rows: [ 'row1 3 here', 'row 4 here' ],
},
table3: {
headings: [ 'what', 'up' ],
rows: [ 'row 5 here', 'row 6 here' ],
},
}


Edit



I am using React and my end goal is for me to construct each table within a Table Component, so I am hoping to be able to something like below within the component

const headings = [ 'hey', 'there' ]
const rows = [ 'row 1 here', 'row 2 here' ]

Answer

If you're asking how to enumerate the data structure, something like this would work:

let tables = {
  table1: {
    headings: ['hey', 'there'],
    rows: ['row 1 here', 'row 2 here'],
  },
  table2: {
    headings: ['sup', 'yall'],
    rows: ['row1 3 here', 'row 4 here'],
  },
  table3: {
    headings: ['what', 'up'],
    rows: ['row 5 here', 'row 6 here'],
  },
};


Object.keys(tables).forEach((tableId) => {

  tables[tableId].headings.forEach((heading) => {
    // do something with heading
  });

  tables[tableId].rows.forEach((row) => {
    // do something with the row
  });
});