功能性Javascript:无法迭代具有嵌套对象和数组的对象

时间:2016-11-10 22:56:09

标签: javascript arrays functional-programming ecmascript-6 ramda.js

我在尝试在如下结构的表格中访问我的数据时遇到了困难。我想要一种通过功能Javascript方法访问我的嵌套数据的干净而有效的方法。如果有人能够展示如何使用Ramda或普通ES6在功能上做到这一点,我们将不胜感激!请参阅下面的示例表结构。

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

修改

我正在使用React,我的最终目标是让我在表组件中构建每个表,所以我希望能够在组件中使用下面的内容 const headings = [ 'hey', 'there' ] const rows = [ 'row 1 here', 'row 2 here' ]

3 个答案:

答案 0 :(得分:1)

如果你问如何枚举数据结构,这样的事情就可以了:

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

答案 1 :(得分:1)

如果您想要做的是转换数据(而不是处理一些副作用),那么Ramda确实有一些工具可以让它更容易,尤其是evolve

如果您有一个想要用于身体元素的功能,例如:

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

你希望大写标题,你可以使用这样的东西

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

您可以在 Ramda REPL 上看到这一点。

答案 2 :(得分:-1)

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

关于在那里循环对象和数组的大量例子