用.map()

时间:2017-01-25 01:25:03

标签: javascript arrays replace google-sheets

使用Google表格的脚本编辑器,我想替换每个表格的数字值,如下所示:

"I like it" = 2
"I don't like it" = -1
"Haven't seen it" = 0   

+---------+-----------------+-----------------+-----------------+
|         |      User A     |     User B      |      User C     |
+---------+-----------------+-----------------+-----------------+
| Movie 1 |    I like it    | I don't like it | Haven't seen it |
+---------+-----------------+-----------------+-----------------+   
| Movie 2 | Haven't seen it | Haven't seen it | I don't like it | 
+---------+-----------------+-----------------+-----------------+
| Movie 3 | Haven't seen it | I don't like it |    I Like it    |
+---------+-----------------+-----------------+-----------------+   

我不确定是否应该使用 array.map() array.forEach()但是,在这两种情况下,我都无法弄清楚将每个单元格与字符串进行比较以创建条件。

如果可能的话,我宁愿避免使用两个 for 循环,因为我相信它必须可以使用 array.map()并且看起来更干净。

2 个答案:

答案 0 :(得分:2)

这是使用map()的另一种方式: (更改工作表名称和范围以适应)。

function stringToNumbers() {

var strings, numbers, range, data, ind;

strings = ['I like it', 'I don\'t like it', 'Haven\'t seen it'];
numbers = [2, -1, 0];
range = SpreadsheetApp.getActive()
    .getSheetByName('Sheet6')
    .getRange('B2:D6')
data = range.getValues()
    .map(function (r) {
        return r.map(function (el) {
            ind = strings.indexOf(el);
            return ind > -1 ? numbers[ind] : null;
        })
    })

Logger.log(data)
//range.setValues(data) //if you want to write the numbers back to the sheet, uncomment this line.
}

答案 1 :(得分:1)

要翻译数组中的所有数据,您可能希望使用Array.prototype.map()。但是,由于我假设您的数据结构是嵌套数组,因此您可能需要使用forEachmap的组合:

var arr = [['I like it', 'I don't like it', 'Haven't seen it'],[//etc]];

function stringToNumber(str) {
  var num;
  if (str === "I like it") {
    num = 2;
  } else if (str === "I don't like it") {
    num = -1;
  } else if (str === "Haven't seen it") {
    num = 0;
  }
  return num;
}

function mapRow(row) {
  return row.map(stringToNumber);
}

arr.forEach(mapRow)