2016-11-22 115 views
0

我有喜歡如何將平行列表的對象轉換爲對象列表?

var data = [ 
    { 
     "Name": ["Jane", "Peter", "Jenny"], 
     "Id": [1, 2, 3], 
     "Years": [16, 17, 18] 
    } 
]; 

的對象,但我希望把它放到一個反應表,需要像另一種格式,它

var data1 = [ 
    { 
    "Name": "Jane", 
    "Id": 1, 
    "Years": 16, 
    }, 
    { 
     "Name": "Peter", 
     "Id": 2, 
     "Years": 17, 
    }, 
    { 
     "Name": "Jenny", 
     "Id": 3, 
     "Years": 18, 
    } 
] 

如何我JSX轉換呢?

+5

你可能會寫一些代碼。你有什麼嘗試? – RobG

+0

如果'Name','Id'和'Years'中的數組沒有相同數量的項目,會發生什麼? – Phil

+0

@Phil我認爲這不會發生,它會讓'0'來使相同數量的項目 –

回答

2

我會找出最大屬性長度(如果它們不完全相同),創建一個大小的數組,在for循環中迭代,使用數據創建對象和匹配索引職位(null如果不匹配)並將其推入陣列。

const data = [{ 
 
    "Name": ["Jane", "Peter", "Jenny"], 
 
    "Id": [1, 2, 3], 
 
    "Years": [16, 17, 18] 
 
}] 
 

 
const interestingData = data[0] 
 
const keys = Object.keys(interestingData) 
 

 
const maxItems = keys.reduce((count, key) => Math.max(count, interestingData[key].length), 0) 
 

 
const transformed = new Array(maxItems) 
 
for (var i = 0; i < maxItems; i++) { 
 
    transformed[i] = keys.reduce((obj, key) => Object.assign(obj, { 
 
    [key]: interestingData[key][i] || null // default value if no matching index 
 
    }), Object.create(null)) 
 
} 
 

 
console.info(transformed)

2

這裏是你的問題非常簡單的實現。對於迭代,我已經考慮了名稱數組內部對象的長度。

var data = [{ 
 
    "Name": ["Jane", "Peter", "Jenny"], 
 
    "Id": [1, 2, 3], 
 
    "Years": [16, 17, 18] 
 
}]; 
 

 
var data1 = [ ]; 
 

 
var iterations = data[0].Name.length; 
 

 
var requiredData = data[0]; 
 

 
var keyArray = Object.keys(requiredData); 
 

 

 
for (var i = 0; i < iterations; i++) { 
 
    tempObj = { }; 
 
    for (var key of keyArray) { 
 
     tempObj[key] = requiredData[key][i]; 
 
    } 
 
    data1.push(tempObj); 
 
} 
 

 
console.log('data1 = ', data1)

相關問題