鑒于示例資料,我需要轉換給定的內容并以表格形式回傳。這是示例資料。我怎樣才能讓輸出變成下面的樣子?
var revisions = {
data:[
// row 1
{
cId: {
value: "123456",
oldValue: null
},
revisionDate:{
value: "09/01/2021",
oldValue: "09/21/2021"
},
revisionType:{
value: "UPDATE",
oldValue: "DELETE"
},
revisionNote:{
value: "Some test note 0",
oldValue: "Old revision note 0"
},
financeNo:{
value: "FA1",
oldValue: "FA2"
}
},
// row 2
{
dccId: {
value: "123457",
oldValue: null
},
revisionDate:{
value: "05/01/2021",
oldValue: "09/28/2021"
},
revisionType:{
value: "NEW",
oldValue: "UPDATE"
},
revisionNote:{
value: "Some test note 1",
oldValue: "Old revision note 1"
},
financeNo:{
value: "FA4",
oldValue: "FA5"
},
maintNo:{
value: "MN001",
oldValue: "MN002"
},
isSpare:{
value: 0,
oldValue: 1
}
},
// row 3 ...
]
}
控制臺輸出應該是:
[
{cId: "123456", revisionDateNew: "09/01/2021", revisionDateOld:"09/21/2021", revisionTypeNew: "UPDATE",revisionTypeOld: "DELETE", revisionNoteNew: "Some test note 0", revisionNoteOld: "Old revision note 0", financeNoNew: "FA1", financeNoOld: "FA2", maintNoNew: "", maintNoOld: "", isSpareNew: "", isSpareOld: ""},
{cId: "123457", revisionDateNew: "05/01/2021", revisionDateOld:"09/28/2021", revisionTypeNew: "NEW", revisionTypeOld: "UPDATE", revisionNoteNew: "Some test note 1", revisionNoteOld: "Old revision note 1", financeNoNew: "FA4", financeNoOld: "FA5", maintNoNew: "MN001", maintNoOld: "MN002", isSpareNew: "0", isSpareOld: "1"},
...
]
到目前為止,這就是我所做的,但我堅持如何不對屬性進行硬編碼,而且我也在努力弄清楚將“新”和“舊”分配給當前屬性所需的邏輯,然后為這些屬性提供正確的值。
function loopData(revisions: any) {
var newData = revisions.data.map(item => ({
cId: item.cId.value,
revisionDateNew: item.revisionDate.value
}))
console.log(newData)
}
我想我需要的是另一個回圈,可能是一個 forEach,我在其中獲取密鑰,然后創建一個新陣列來推送新欄位。
uj5u.com熱心網友回復:
我經常使用的一個通用函式objectMap將物件中的每個欄位映射到其他一些資料:
/**
* similar to Array.map but for the fields of an object.
* the callback takes the value as first argument and key as second.
* does not support passing object as 3rd argument or thisArg.
*/
export function objectMap<T, V>(obj: T, fn: (val: T[keyof T], key: keyof T) => V) {
// this is one of the cases where the as Record followed by a loop initializing all the keys
// the whole reason this function exists is to have this typesafe outside :)
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
const newObj = {} as Record<keyof T, V>;
for (const [key, val] of Object.entries(obj)) {
newObj[key as keyof T] = fn(val, key as keyof T);
}
return newObj;
}
有了這個,你可以在這個操場上獲得正確的資料結構
const newData = revisions.data.map(v=>objectMap(v, x=>x?.value))
請注意,它不會完全保留型別,因為我們通常需要此功能來正確鍵入它,您可能需要一個介面來表示輸出的型別,因此這對您來說可能不是問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/364776.html
標籤:数组 打字稿 for循环 目的 数组.prototype.map
