A possible approach, which also allows flexible adaption and code-reuse, takes advantage of the so often overlooked optional second argument, one is allowed to provide to most array methods ... thisArg
for e.g. map
.
Thus, such an approach does create a lookup table from the OP's headers
list and does provide it to the mapping process since one does not want to search (within each iteration step of map
) always again and again the same list in order to find the correct/matching related conversion type
.
The actual mapping then will be easy. Implement a function which assumes its this
context to be a lookup table and which does (re)create a type-converted version of the provided (here currently processed) object by looking up the correct conversion type
before providing it to the OP's convertData
function.
const convertData = (type, value) => {
switch (type) {
case "date": {
return new Date(Number(value)).toDateString();
}
case "currency": {
return value ? `$${value}` : null;
}
default:
return value;
}
};
const headers = [{
field: 'amount',
type: 'currency'
}, {
field: 'deliveredDate',
type: 'date'
}];
const body = [{
id: 1,
amount: 4000,
deliveredDate: "1610427600000"
}, {
id: 2,
amount: 6000,
deliveredDate: "1611118800000"
}];
function createConversionTypeLookupTable(conversionTypeList) {
return conversionTypeList.reduce((table, conversionTypeItem) => {
table[conversionTypeItem.field] = conversionTypeItem.type;
return table;
}, {});
}
function createConvertedItemViaBoundLookupTable(item) {
const lookupTable = (this || {}); // more fail safe.
return Object.entries(item).reduce((obj, [key, value]) => {
obj[key] = convertData((lookupTable[key] || key), value);
return obj;
}, {});
}
console.log(
'Converted Item List ...',
body.map(
createConvertedItemViaBoundLookupTable,
createConversionTypeLookupTable(headers)
)
);
console.log(
'Conversion Type Lookup Table ...',
createConversionTypeLookupTable(headers)
);
.as-console-wrapper { min-height: 100%!important; top: 0; }
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…