RuNpiXelruN
RuNpiXelruN

Reputation: 1920

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' ]

Upvotes: 0

Views: 88

Answers (3)

Scott Sauyet
Scott Sauyet

Reputation: 50807

If what you want to do is to transform the data (as opposed to process some side-effects on it), then Ramda does have some tools to make it easier, especially evolve.

If you had a function that you wanted to used for the body elements such as this:

const surround = (tag) => (content) => `<${tag}>${content}</${tag}>`;

and you wanted to upper-case the headers, you could use something like this

R.map(R.evolve({
  headings: R.map(R.toUpper),
  rows: R.map(surround('td'))
}))(tables);

You can see this in action on the Ramda REPL.

Upvotes: 1

skav
skav

Reputation: 1460

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
  });
});

Upvotes: 1

Lockless
Lockless

Reputation: 497

for (var key in tables ) {
    for (var innerKey tables[key] ) {
        for (var i = 0; i < tables[key][innerKey].length; i++) {
            console.log(tables[key][innerKey][i]);
        }
    }   
}

Plenty of examples on looping over objects and arrays out there

Upvotes: -1

Related Questions