如何使用参数传递的函数遍历复杂的对象来格式化给定的必填字段?

问题描述

我正在尝试创建一个通过复杂对象的函数,该函数会格式化数组中的给定字段。

该函数必须接收必须格式化的对象,然后下一个参数是具有必须被格式化的属性的数组,最后最后一个函数接收将对字段值进行格式化的函数。

该函数必须以其原始结构返回对象。

直到现在我的代码:

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'
    }
  ]
}

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...