javascript - 使用 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 |
因为它AA
在Other 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]));
}
}
解决方案
如果您只是更改要检索的范围,则从上一个问题中获得的代码可以正常工作。因此,您无需创建将列提取到数组中的函数,只需调整范围即可。
如果要替换的列('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));
推荐阅读
- java - react js站点可以用机器人框架自动化吗?
- javascript - 无法正确地将 JS obj 值附加到动态创建的 div 中
- java - Powermock junit5 和 mockito2.x 不工作 RunnerTestSuiteChunker not found
- python - 通过 Flask 处理 ChartJS
- java - 突然找不到 Eclipse 类
- java - 添加数组的所有元素,除了索引处的元素,复杂度为 O(n)
- flutter - 耀斑动画图标的尺寸太小
- c# - 如何使按钮在传递所有鼠标事件的半透明路径几何图形上可点击?
- vb.net - Selenium instagram 照片上传不会发生
- css - 使用绝对定位使按钮显示在容器外部