Find Replace all values in a column Google script/JavaScript

丶灬走出姿态 提交于 2021-01-29 06:06:21

问题


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")];
  }
 
}

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 = ["This", "That", "The other"];

and replace them with a different list

var ireplace = ["AAA", "BBB", "CCC"];

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

Thanks


回答1:


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>


来源:https://stackoverflow.com/questions/65041222/find-replace-all-values-in-a-column-google-script-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!