如何解决如何使用参数传递的函数遍历复杂的对象来格式化给定的必填字段?
我正在尝试创建一个通过复杂对象的函数,该函数会格式化数组中的给定字段。
该函数必须接收必须格式化的对象,然后下一个参数是具有必须被格式化的属性的数组,最后最后一个函数接收将对字段值进行格式化的函数。
该函数必须以其原始结构返回对象。
直到现在我的代码:
const formatFields = (obj = {}) => (fieldsToFormat = []) => (formatFunction = () => {}) => {
let newObj = { ...obj };
for (let [k,v] of Object.entries(obj)) {
if (typeof v === 'object' && v !== null) formatFields(v)(fieldsToFormat)(formatFunction);
if (fieldsToFormat.includes(k)) newObj = { ...newObj,[k]: formatFunction(v) };
else newObj = { ...newObj,[k]: v };
}
return newObj;
}
const toMoney = (num) => '$' + num;
const obj = {
totalAmount: 83.24,quoteItems:
[ { max: '1',code: '1',quantity: 1,unitPrice: 23.21,totalPrice: 23.21,description: 'test'
},{
max: '3',code: '2',quantity: 3,unitPrice: 20.01,totalPrice: 60.03,description: 'test2'
} ],};
const priceFormatAttributes = [
'unitPrice','totalPrice','totalAmount'
];
console.log(formatFields(obj)(priceFormatAttributes)(toMoney));
嵌套对象未格式化!
我知道这是一个逻辑问题,这是一个挑战,我无法继续前进。
我认为递归是错误的,但我不知道为什么!
如果有人对如何以其他方式解决此问题有想法,也欢迎您。
解决方法
虽然我不确定预期的输出是多少,但我会尝试这样做:
const formatFields = (obj = {}) => (fieldsToFormat = []) => (formatFunction = () => {}) => {
let newObj = { ...obj }; // clone object to prevent changing the original object
if (Array.isArray(obj)) { // gotta deal with arrays too unless you want to change them all into objects
newObj = [ ...obj ];
}
for (let [key,value] of Object.entries(obj)) {
if (Array.isArray(newObj)) {
newObj.splice(key - 1,1); // remove the previous it
newObj.push(formatFields(value)(fieldsToFormat)(formatFunction));
}
else if (typeof value === 'object' && value !== null) {
newObj = { ...newObj,[key]: formatFields(value)(fieldsToFormat)(formatFunction) };
}
else if (fieldsToFormat.includes(key)) {
newObj[key] = formatFunction(value)
}
else newObj = { ...newObj,[key]: value };
}
return newObj;
}
const toMoney = (num) => {
return '$' + num;
}
const obj = {
totalAmount: 83.24,quoteItems: [
{
max: '1',code: '1',quantity: 1,unitPrice: 23.21,totalPrice: 23.21,description: 'test',},{
max: '3',code: '2',quantity: 3,unitPrice: 20.01,totalPrice: 60.03,description: 'test2',}
],};
const priceFormatAttributes = [
'unitPrice','totalPrice','totalAmount',];
console.log(formatFields(obj)(priceFormatAttributes)(toMoney));
这将输出:
{
totalAmount: '$83.24',quoteItems: [
{
max: '1',unitPrice: '$23.21',totalPrice: '$23.21',description: 'test'
},{
max: '3',unitPrice: '$20.01',totalPrice: '$60.03',description: 'test2'
}
]
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。