查找替换列Google脚本/JavaScript中的所有值 [英] Find Replace all values in a column Google script/JavaScript
问题描述
我需要在一列的所有单元格中找到多个值,并将它们替换为不同的值
I need to find multiple values in all cells in a column and replace them with different values
如果我只有一个值可以查找/替换我的函数,那么效果很好
IF I only have one value to find/replace my function works great
function FindReplace() {
var ss = SpreadsheetApp.getActiveSheet();
var col = [].concat.apply([], ss.getRange(2,3,ss.getLastRow()).getValues());
ss.getRange(2,3,ss.getLastRow()).setValues(col.map(fr));
function fr(input){
return [input.replace("something","something else")];
}
}
但是我需要找到列表中的所有值,并从另一个列表中替换它们,列表中可以包含n个元素
But I need to find all values in a list and replace them from a different list the lists can have n elements
var ifind = [这个",那个",另一个"];
并将它们替换为其他列表
and replace them with a different list
var ireplace = ["AAA","BBB","CCC"];
我一直在尝试在下面使用map()或forEeach()来执行此操作,但无济于事
I have been trying to use map() or forEeach() within the following to do this but to no avail
function findreplace(input){
var ifind = ["This", "That", "The other"];
var ireplace = ["AAA", "BBB", "CCC"];
return [input.replace(ifind ,ireplace)];
}
我知道我可以在整个过程中使用循环,但是尝试学习新事物,这看起来很有希望,或者至少是一种有趣的方法
I know I can use a loop for the whole process but trying to learn new things and this looked promising or at least an interesting approach
谢谢
推荐答案
对象或Map 对于1对1的关系将是更好的数据结构.您可以将其与 Array#reduce 遍历对象中的所有键,并用一个键替换一个键,累积结果:
A object or Map would be a better data structure for 1 to 1 relationships. You can use it along with Array#reduce to loop over all keys in the object and replace it one by one accumulating the result:
function findReplace_mod1() {
const ss = SpreadsheetApp.getActiveSheet();
/*No flat*/ const col = /* [].concat.apply([], */ ss
.getRange(2, 3, ss.getLastRow())
.getValues(); /* ) */
const map = { This: 'AAA', That: 'BBB' };
const iFinds = Object.keys(map);
ss.getRange(2, 3, ss.getLastRow()).setValues(col.map(fr));
function fr(input) {
return [iFinds.reduce((str, k) => str.replace(k, map[k]), input[0])];
}
}
/*<ignore>*/console.config({maximize:true,timeStamps:false,autoScroll:false});/*</ignore>*/
function findReplace_mod1() {
const col = [['This is a cat'], ['This is not That']];
const map = { This: 'AAA', That: 'BBB' };
const iFinds = Object.keys(map);
console.info(col.map(fr));
function fr(input) {
return [iFinds.reduce((str, k) => str.replace(k, map[k]), input[0])];
}
}
findReplace_mod1();
<!-- https://meta.stackoverflow.com/a/375985/ --> <script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
这篇关于查找替换列Google脚本/JavaScript中的所有值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!