首页 > 解决方案 > 使用 map() 将查找和替换函数限制为二维数组 JavaScript 中的单列

问题描述

我在 Google 工作表中工作

我有一个从这里得到的查找和替换功能。当数组由单列数据组成时效果很好

但是,在某些我想使用我的函数的情况下,我将所有数据放在一个数组中,该数组是从先前处理传递的,如果打印到页面上,数据看起来像

| Id | Segment            |Other Column| etc..
|----|--------------------|------------|
| 1  | AAA AA|AA|CaaL AA  |stuff       |
| 2  | AAA-AA|AA|CaaL     |stuff       |
| 3  | AAA, AA|AA|AA      |AA          |
| 4  | AA                 |stuff       | 
| 5  | AA AA              |            |
| 6  | AA, AA             |AA          |
| 7  |                    |stuff       |
| 8  | CaaL               |stuff       |
| 9  | AA                 |stuff       |

我只想替换Segment列中的数据

| Id | Segment           ||Other Column| etc..
|----|-------------------|------------|
| 1  | AAA AA|zz|CaaL AA |stuff       |
| 2  | AAA-AA|zz|Bob     |stuff       |
| 3  | AAA, AA|zz|zz     |AA          |
| 4  | zz                |stuff       |
| 5  | AA AA             |            |
| 6  | AA, AA            |AA          |
| 7  |                   |stuff       |
| 8  | Bob               |stuff       |
| 9  | zz                |stuff       |

因为它AAOther Column(可能在任何列中,我无法知道)正在被替换,我不想要

是否可以将 findReplace 函数限制为仅更新该列的值中的单个列values

我已经尝试获取要限制值的列数组

function getColumn(matrix, col, startrow){
       var column = [];
       for(var i=startrow; i<matrix.length; i++){
          column.push(matrix[i][col]);
       }
       return column;
}

然后尝试将输入限制在此列


function fr(input) {
    const aCOL = getColumn(values,2,0)
    return input.aCOL.map(c => c.replace(regex, (x) => map[x]));
    
AND
   
   return input.map(c => c.aCOL.map(y => y.replace(regex, (x) => map[x])));

  }

我明白了 Cannot read property 'map' of undefined

谢谢

function findReplace(values) {

  var search_for   = ["AA", "Caal"];
  var replace_with = ["zz", "yy"];
  
  var map = {};
  search_for.forEach(function(item, i) {
    map[item] = replace_with[i];
  });
  //map = { AA: 'zz', Caal: 'yy' };

  const regex = new RegExp("(?<![^|])(?:" + search_for.join("|") + ")(?![^|])", "g");
  
  range.setValues(values.map(fr));

  function fr(input) {
    return input.map(c => c.replace(regex, (x) => map[x]));
  }
}  

标签: javascriptarraysdictionarygoogle-apps-script

解决方案


如果您只是更改要检索的范围,则从上一个问题中获得的代码可以正常工作。因此,您无需创建将列提取到数组中的函数,只需调整范围即可。

如果要替换的列('Segment')是第二个,则可以进行以下更改。

从:

const col = ss.getRange(2, 3, ss.getLastRow()).getValues();
...
ss.getRange(2, 3, ss.getLastRow()).setValues(col.map(fr));

至:

const col = ss.getRange(2, 2, ss.getLastRow()).getValues();
...
ss.getRange(2, 2, ss.getLastRow()).setValues(col.map(fr));

推荐阅读