映射元素匹配字符串

Mapping over elements matching string

我有地图

.map((item: { amount: number}) =>

问题是对象道具并不总是数量,而是从数量开始。所以它可能是

.map((item: { amountTotal: number}) =>

.map((item: { amountConsolidated: number}) =>

有没有办法对字符串进行正则表达式或部分匹配,以便 map 函数可以覆盖所有对象名称?

不,你不能那样做。解构只适用于具体的键,它不能变形来改变基于数据解构的键。

如果您有一个混合数据数组 ,其中只有一个 属性存在,您可以解构所有属性,然后获取包含数据的那个。这样你就可以对数组中的所有项目进行操作:

const data = [
  {amount:             1}, 
  {amountTotal:        2},
  {amountConsolidated: 3},
];

const result = data.map(({amount, amountTotal, amountConsolidated}) => {
  //pick the first one that exists
  const num = amount ?? amountTotal ?? amountConsolidated;
  
  //example mapping operation
  return num * 2;
});

console.log(result);


或者,如果您有一个同质数组,其中数据的形状完全相同,您可以创建一个函数来处理普通值,然后您可以指定它应该从哪个 属性 中获取它:

const data1 = [
  {amount: 1}, 
  {amount: 1},
  {amount: 1},
];

const data2 = [
  {amountTotal: 2}, 
  {amountTotal: 2},
  {amountTotal: 2},
];

const data3 = [
  {amountConsolidated: 3}, 
  {amountConsolidated: 3},
  {amountConsolidated: 3},
];

//curried mapper that will apply a function against a given property
const mapper = fn => prop => item =>
  fn(item[prop]);

//use a function that works with plain numbers
const someMappingOperation = mapper(num => num * 2);

//specify which property the number comes from depending on the array
const result1 = data1.map(someMappingOperation("amount"));
const result2 = data2.map(someMappingOperation("amountTotal"));
const result3 = data3.map(someMappingOperation("amountConsolidated"));

console.log(result1);
console.log(result2);
console.log(result3);