打字稿 - 对象投影

Typescript - object projection

以“点符号”格式将任意对象数组和路径数组作为字符串,是否可以投影到新对象?

例如给定一个数组 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) 使用所选路径进行序列化。

您可以递归地遵循这些路径,然后始终沿着最后一条路径传递对象。例如:

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;
});