2016-12-04 66 views
-1

我的ajax響應中有一個多維對象。這裏是對象如何將多維對象轉換爲javascript中的表格行列格式

response = { 
      "Bangladesh": { 
       "2016": 5, 
       "2017": 1 
      }, 
      "Nepal": { 
       "2016": 1, 
       "2019": 10 
      } 
    }; 

現在我想重新安排陣列到谷歌圖表數據表格式波紋管

['Year', 'banglladesh', 'nepal' ], 
['2016', 5,1], 
['2017', 1,0], 
['2019', 0, 10], 
+0

你試過的是什麼? –

+0

你試過了什麼? ['Object'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#Methods_of_the_Object_constructor)和['Array'](https:// developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Methods_2)方法或使用簡單的'for'循環。 – Xufox

回答

2

那是很難的,我敢肯定,這可以改善。看評論

const response = { 
 
    "Bangladesh": { 
 
    "2016": 5, 
 
    "2017": 1 
 
    }, 
 
    "Nepal": { 
 
    "2016": 1, 
 
    "2019": 10 
 
    } 
 
}; 
 

 
const parse = val => isNaN(val) ? val : Number(val) 
 

 
const tablerize = (obj, unique) => { 
 
    const columns = Object.keys(obj) 
 
    const table = [[unique, ...columns]] 
 
    // indexed by the unique key 
 
    const indexed = {} 
 
    
 
    // sort by the index 
 
    columns.forEach((key, ii) => { 
 
    return Object.keys(obj[key]).forEach((prop) => { 
 
     if (!indexed[prop]) { 
 
     indexed[prop] = {} 
 
     } 
 
     indexed[prop][ii] = obj[key][prop] 
 
    }) 
 
    }) 
 
    
 
    // add to the output table 
 
    Object.keys(indexed).forEach(key => { 
 
    table.push([ 
 
     parse(key), 
 
     // return the value at the key index 
 
     ...columns.map((k, ii) => parse(indexed[key][ii]) || 0) 
 
    ]) 
 
    }) 
 
    
 
    return table 
 
} 
 

 
console.log(
 
    tablerize(response, 'Year') 
 
)
<script src="http://codepen.io/synthet1c/pen/WrQapG.js"></script>

+0

非常感謝。它會按我的預期工作 –

0

不知道什麼數字陣列中的第三個項目是基於提供的響應即將到來,但至少這將讓你在正確的方向:

var response = { 
    "Bangladesh": { 
     "2016": 5, 
     "2017": 1 
    }, 
    "Nepal": { 
     "2016": 1, 
     "2019": 10 
    } 
}; 

var out = []; 

var header = ["Year"]; 
out.push(header); 

for(var prop in response){ 
    header.push(prop); 
    var item = response[prop]; 
    for(var year in item){ 
     out.push([year, item[year] ]); 
    } 
} 

console.log(out); 
+0

謝謝。這將有助於我作出進一步的決定 –

相關問題