簡體   English   中英

功能性Javascript:遍歷具有嵌套對象和數組的對象時遇到麻煩

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

我在嘗試訪問如下結構的表中的數據時遇到困難。 我想要一種干凈有效的方法,通過功能性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' ]

如果您詢問如何枚舉數據結構,則可以執行以下操作:

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

如果您想要做的是轉換數據(而不是處理數據上的一些副作用),那么Ramda確實有一些工具可以使數據變得更容易,尤其是evolve

如果您有想要用於諸如此類的body元素的函數:

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

而您想將標題大寫,則可以使用如下所示的內容

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

您可以在Ramda REPL上看到這一點。

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

關於遍歷對象和數組的大量示例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM