简体   繁体   English

如何将Map.get()与数组一起使用

[英]How to use Map.get() with array of arrays

Is there any way to use Map.get() with an array of arrays (specifically in d3.js)? 有什么方法可以将Map.get()与数组数组一起使用(特别是在d3.js中)?

Here's what I have: (1) Map – containing data in over 100 key-value pairs (2) Array of arrays – listing the keys of the data I want to pull from the Map for populating a table (only a subset of the 100+ values) 这就是我所拥有的:(1)Map –包含超过100个键值对的数据(2)数组数组–列出了我想从Map中提取以填充表格的数据的键(仅是100个的子集) +值)

Here's what I need to create: (1) A new array of arrays – this new array should take each item from the first array in turn, look up the key in the Map and return the value. 这是我需要创建的:(1)一个新的数组数组–该新数组应依次从第一个数组中获取每个项目,在Map中查找键并返回值。

I can get Map.get() to work just fine over a single array, but only if I specify the index of the nested array, like this: 我可以使Map.get()在单个数组上正常工作,但前提是我指定嵌套数组的索引,如下所示:

var myMap;
var dataArray = [key_1, key_2, key_3, key_4, key_5, key_6]
var newArray = dataArray[0].map(function(d) {
              return myMap.get(d);
              });

But when my original array is an array of arrays, I can't figure out how to do it: 但是,当我的原始数组是数组数组时,我不知道该怎么做:

var myMap;
var dataArray = [
   [key_1, key_2, key_3],
   [key_4, key_5, key_6],
   [key_7, key_8, key_9]
   ]
var newArray = ???

Any suggestions? 有什么建议么?

You have nested arrays, so use nested map s: 您具有嵌套数组,因此请使用嵌套map

var newArray = dataArray.map(function(array) {
                   return array.map(function(d) {
                       return myMap.get(d);
                   });
               });

If creating functions in loops bothers you, you can split the recreated function out: 如果在循环中创建函数使您感到困扰,则可以将重新创建的函数分开:

var newArray = dataArray.map(function(array) {
                   return array.map(mapOne);
               });
function mapOne(array) {
    return array.map(function(d) {
        return myMap.get(d);
    });
}

Not only or 2D but for an indefinite ND array of keys you may also do as follows; 不仅是2D,而且对于不确定的ND键数组,您还可以执行以下操作:

 var myMap = new Map(), dataArray = [["key_1", "key_2", ["key_31", "key_32", ["key_331"]]], ["key_4", "key_5", ["key_61", "key_62", ["key_631"]]], ["key_7", "key_8", ["key_91", "key_92", ["key_931"]]] ], getMap = (a,m) => a.map(k => Array.isArray(k) ? getMap(k,m) : m.get(k)); console.log(JSON.stringify(getMap(dataArray,myMap))); 

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

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