2017-08-28 40 views
0

我想JSON格式轉換在JavaScript這樣的:如何在反應JS中轉換格式json?

{ 
    "a": [5,1,2], 
    "b": [4,0,3], 
    "c": [1,1,4] 
} 

[ 
    {'a':5,'b':4,'c':1}, 
    {'a':1,'b':0,'c':1}, 
    {'a':2,'b':3,'c':4} 
] 

如何解決這個問題?

+0

你可以分享你嘗試過什麼做呢? – marvel308

+0

請參閱[如何提出一個好問題](https://stackoverflow.com/help/how-to-ask)部分。你有什麼嘗試,你有代碼?閱讀[如何創建最小,完整和可驗證示例](https://stackoverflow.com/help/mcve)。 –

回答

0

在這裏你去:

const obj = { 
 
    "a": [5,1,2], 
 
    "b": [4,0,3], 
 
    "c": [1,1,4] 
 
}; 
 

 
const convert = (obj) => { 
 
    let res = []; 
 
    const keys = Object.keys(obj); 
 
    if (!keys.length) return []; 
 
    for (let i = 0; i < obj[keys[0]].length; i++) { 
 
    let nextObj = {}; 
 
    keys.forEach(key => { 
 
     nextObj[key] = obj[key][i]; 
 
    }); 
 
    res.push(nextObj); 
 
    } 
 
    return res; 
 
} 
 

 
console.log(convert(obj))

+0

沒問題@ user3440030:D – Zevgon

0

您可以通過以下方式

let obj = { 
 
"a": [5,1,2], 
 
"b": [4,0,3], 
 
"c": [1,1,4] 
 
} 
 

 
let result = [], idx=0; 
 
while(true){ 
 
    let isValid = true, tempObj = {}; 
 
    for(element in obj){ 
 
     if(idx < obj[element].length){ 
 
      tempObj[element] = obj[element][idx]; 
 
     } 
 
     else{ 
 
      isValid = false; 
 
     } 
 
    } 
 
    if(isValid){ 
 
     result.push(tempObj); 
 
    } 
 
    else{ 
 
     break; 
 
    } 
 
    idx++; 
 
} 
 

 
console.log(result);