简体   繁体   English

从分配给 Map Object 的键的数组中提取数组元素

[英]Extract Array Elements from an Array assigned to a Key of a Map Object

I have added an Array of 2 dates to a Key of a new Map object.我已将 2 个日期的数组添加到新的 Map object 的键中。 I want to access these individual dates and store them in columns 3 & 16 of another sheet viz ShtStudy .我想访问这些单独的日期并将它们存储在另一张表的第 3 列和第 16 列中,即ShtStudy Here is a snippet of the code:这是代码片段:

ShtFC: ShtFC:

ID    | Name | Sol  | Own  | Acct  | Date1      | Date2      |
10000 | abc  | sol1 | own1 | acct1 | 09/01/2020 | 10/02/2020 |
10003 | def  | sol3 | own3 | acct3 | 01/05/2020 | 03/10/2020 |

ShtStudy:研究:

Name  |  ID  |  Date1     | Sol  | Col.... | Col 15 | Date2      | .... |
abc   |10001 | 09/01/2020 | sol1 | .....   | .....  | 10/02/2020 | .... |
def   |10003 | 01/05/2020 | sol3 | .....   | .....  | 03/10/2020 | .... |

Code Snippet:代码片段:

r_Study = FindLastRow(shtStudy);
r_FC = FindLastRow(shtFC);
let StudyRng = shtStudy.getRange(2, 1, r_Study - 2 + 1, c_Study);
let FCRng = shtFC.getRange(2, 1, r_FC - 2 + 1, 7).getValues();

const idMap = FCRng.reduce( (mp, [id,,,,,date,date1]) => mp.set(id, [date, date1]), new Map );
const SRng = StudyRng; //shtStudy.getDataRange();
const svalues = SRng.getValues();
svalues.forEach(row => {
  console.log(idMap.get(row[1])[0]);  //===> This does not work
  console.log(idMap.get(row[1])[1]);  //===> This does not work

  row[2]  = idMap.get(row[1])[0] || row[2];
  row[15] = idMap.get(row[1])[1] || row[15];
});
SRng.setValues(svalues);

I tried using Slice method also to access the individual dates in the array, but does not seem to work.我也尝试使用Slice方法来访问数组中的各个日期,但似乎不起作用。

idMap.get(row[1]).slice(0)
idMap.get(row[1]).slice(1)

If i just use the below line, i get to see the Array with the 2 dates:如果我只使用下面的行,我会看到带有 2 个日期的数组:

idMap.get(row[1])

Output: Output:

[ Wed Aug 19 2020 00:00:00 GMT-0400 (Eastern Daylight Time),
  Thu Sep 03 2020 00:00:00 GMT-0400 (Eastern Daylight Time) ]

idMap 对象

In some cases the expression idMap.get(row[1]) will be undefined.在某些情况下,表达式idMap.get(row[1])将是未定义的。 This happens when an id in the second table does not match with one in the first.当第二个表中的 id 与第一个表中的不匹配时,就会发生这种情况。 And when it is undefined, you cannot append [0] to that expression.当它未定义时,你不能 append [0] 到那个表达式。

There is the optional chaining operator operator you can use for that case:对于这种情况,您可以使用可选的链接运算符:

row[2]  = idMap.get(row[1]).?[0] || row[2];

If you have no support for that operator, then:如果您不支持该运算符,则:

let match = idMap.get(row[1]);
row[2]  = match ? match[0] : row[2];

You should of course do the same thing for the assignment to row[15] .您当然应该对row[15]的分配做同样的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM