Search code examples
javascriptregextemplate-literalsarray-map

Mapping over elements matching string


I have a map

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

The issue is that object prop is not always amount but will start with that. so it could be

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

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

Is there a way to regex or partially match the string so the map function can cover all the object names?


Solution

  • No, you cannot do that. Destructuring only works with concrete keys, it cannot morph to change the key destructured based on the data.

    If you have an array of mixed data where only one of the properties would be present, you can destructure all and then get the one with data. That way you can operate on all the items in the array:

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


    Alternatively, if you have a homogenous array where the data is all the same shape, you can create a function that will work with a plain value and then you can specify which property it should take it from:

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