【问题标题】:Typescript - object projection打字稿 - 对象投影
【发布时间】:2021-10-22 04:06:41
【问题描述】:

以“点符号”格式将任意对象数组和路径数组作为字符串提供有没有办法投影到新对象?

例如给定一个数组 people 和一个路径列表(点表示法):

const people = [
  {
    firstName: 'John',
    lastName: 'Doe',
    address: {
      city: 'New York',
      country: 'US'
    }
  },
  {
    firstName: 'Sally',
    lastName: 'Jane',
    address: {
      city: 'Londaon',
      country: 'UK'
    }
  }
] as Person[]

const paths = ['firstName','address.country'];

有没有办法使用Array.map(p => ???) 仅使用提供的路径进行动态投影?上述结果最终会是:

[
  {
    firstName: 'John',
    address: {
      country: 'US'
    }
  },
  {
    firstName: 'Sally',
    address: {
      country: 'UK'
    }
  }
]

我的最终目标是获取对象数组并使用JSON.stringify(people) 使用选定的路径进行序列化。

【问题讨论】:

    标签: typescript projection


    【解决方案1】:

    您可以递归地跟随路径,然后总是沿着最后一条路径的对象传递。例如:

    function followPath(obj: any, pathParts: string[]): any {
      const result: { [k: string]: any } = {};
    
      const firstPath = pathParts.shift();
      if (firstPath === undefined) {
        return {};
      }
    
      if (pathParts.length > 0) {
        result[firstPath] = followPath(obj[firstPath], pathParts);
      } else {
        result[firstPath] = obj[firstPath];
      }
    
      return result;
    }
    
    
    const paths = ['firstName', 'address.country'];
    
    const newArray = oldArray.map((v) => {
      const newObject = {};
    
      for (const path of paths) {
        const parts = path.split('.');
        const firstPath = parts.shift();
        if (firstPath === undefined) {
          continue;
        }
        
        newObject[firstPath] = parts.length > 0
          ? followPath(v[firstPath], parts)
          : v[firstPath];
      }
    
      return newObject;
    });
    

    【讨论】:

    • 这很好用 - 谢谢。我在分配给 newObject[firstPath] 时确实添加了一个空检查,因为有时这些字段是空的(这不是问题的一部分)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-24
    • 2023-03-07
    • 1970-01-01
    • 2017-06-12
    • 2017-02-18
    • 1970-01-01
    相关资源
    最近更新 更多