ecmascript 6-.map()Javascript ES6 Map?

你会怎么做? 本能地,我想做:

var myMap = new Map([["thing1", 1], ["thing2", 2], ["thing3", 3]]);

// wishful, ignorant thinking
var newMap = myMap.map((key, value) => value + 1); // Map { 'thing1' => 2, 'thing2' => 3, 'thing3' => 4 }

从新的迭代协议的文档中我没有得到太多帮助。

我知道wu.js,但是我正在运行一个Babel项目,并且不想包含Traceur,它似乎当前依赖于Traceur。

对于如何将fitzgen / wu.js如何提取到我自己的项目中,我也一无所知。

很想清楚,简洁地说明我在这里缺少什么。 谢谢!


仅供参考,用于ES6地图的文档

neezer asked 2019-10-09T08:13:13Z
11个解决方案
49 votes

因此Array.from本身仅提供您关心的一个价值...也就是说,有几种解决方法:

// instantiation
const myMap = new Map([
  [ "A", 1 ],
  [ "B", 2 ]
]);

// what's built into Map for you
myMap.forEach( (val, key) => console.log(key, val) ); // "A 1", "B 2"

// what Array can do for you
Array.from( myMap ).map(([key, value]) => ({ key, value })); // [{key:"A", value: 1}, ... ]

// less awesome iteration
let entries = myMap.entries( );
for (let entry of entries) {
  console.log(entry);
}

请注意,在第二个示例中,我使用了很多新东西。... Array.from进行任何迭代(只要您使用[].slice.call( ),再加上Sets和Maps)并将其转换为数组... ...将地图强制转换为数组后,将转换为数组,其中el[0] === key && el[1] === value; (基本上,与我在上面示例地图中填充的格式相同)。

我在lambda的参数位置使用数组的结构分解,以将这些数组点分配给值,然后为每个el返回一个对象。

如果您在生产中使用Babel,则需要使用Babel的浏览器polyfill(包括“ core-js”和Facebook的“ regenerator”)。
我可以肯定它包含Array.from

Norguard answered 2019-10-09T08:13:53Z
23 votes

您应该只使用Spread运算符:

var myMap = new Map([["thing1", 1], ["thing2", 2], ["thing3", 3]]);

var newArr = [...myMap].map(value => value[1] + 1);
console.log(newArr); //[2, 3, 4]

var newArr2 = [for(value of myMap) value = value[1] + 1];
console.log(newArr2); //[2, 3, 4]

Walter Chapilliquen - wZVanG answered 2019-10-09T08:14:24Z
14 votes

只需使用Array.from(iterable, [mapFn])

var myMap = new Map([["thing1", 1], ["thing2", 2], ["thing3", 3]]);

var newArr = Array.from(myMap.values(), value => value + 1);
loganfsmyth answered 2019-10-09T08:14:48Z
1 votes

实际上,在使用2561397764760536036065转换为数组之后,您仍然可以拥有带有原始密钥的Map。这可以通过返回一个数组来实现,其中第一项是2561397764760536036066,第二项是转换后的25613977647605360360。

const originalMap = new Map([
  ["thing1", 1], ["thing2", 2], ["thing3", 3]
]);

const arrayMap = Array.from(originalMap, ([key, value]) => {
    return [key, value + 1]; // return an array
});

const alteredMap = new Map(arrayMap);

console.log(originalMap); // Map { 'thing1' => 1, 'thing2' => 2, 'thing3' => 3 }
console.log(alteredMap);  // Map { 'thing1' => 2, 'thing2' => 3, 'thing3' => 4 }

如果不将该键作为第一个数组项返回,则松开Map键。

mayid answered 2019-10-09T08:15:22Z
0 votes

const mapMap = (callback, map) => new Map(Array.from(map).map(callback))

var myMap = new Map([["thing1", 1], ["thing2", 2], ["thing3", 3]]);

var newMap = mapMap((pair) => [pair[0], pair[1] + 1], myMap); // Map { 'thing1' => 2, 'thing2' => 3, 'thing3' => 4 }

David Braun answered 2019-10-09T08:15:48Z
0 votes

使用Array.from,我编写了一个Typescript函数来映射值:

function mapKeys<T, V, U>(m: Map<T, V>, fn: (this: void, v: V) => U): Map<T, U> {
  function transformPair([k, v]: [T, V]): [T, U] {
    return [k, fn(v)]
  }
  return new Map(Array.from(m.entries(), transformPair));
}

const m = new Map([[1, 2], [3, 4]]);
console.log(mapKeys(m, i => i + 1));
// Map { 1 => 3, 3 => 5 }
saul.shanabrook answered 2019-10-09T08:16:15Z
0 votes

如果您不想事先将整个Map转换为数组和/或分解键值数组,则可以使用以下愚蠢的函数:

/**
 * Map over an ES6 Map.
 *
 * @param {Map} map
 * @param {Function} cb Callback. Receives two arguments: key, value.
 * @returns {Array}
 */
function mapMap(map, cb) {
  let out = new Array(map.size);
  let i = 0;
  map.forEach((val, key) => {
    out[i++] = cb(key, val);
  });
  return out;
}

let map = new Map([
  ["a", 1],
  ["b", 2],
  ["c", 3]
]);

console.log(
  mapMap(map, (k, v) => `${k}-${v}`).join(', ')
); // a-1, b-2, c-31984

mpen answered 2019-10-09T08:16:49Z
0 votes
Map.prototype.map = function(callback) {
  const output = new Map()
  this.forEach((element, key)=>{
    output.set(key, callback(element, key))
  })
  return output
}

const myMap = new Map([["thing1", 1], ["thing2", 2], ["thing3", 3]])
// no longer wishful thinking
const newMap = myMap.map((value, key) => value + 1)
console.info(myMap, newMap)

避免编辑原型取决于您的宗教热情,但是,我发现这让我保持了直观性。

Commi answered 2019-10-09T08:17:17Z
0 votes

我更喜欢扩展地图

export class UtilMap extends Map {  
  constructor(...args) { super(args); }  
  public map(supplier) {
      const mapped = new UtilMap();
      this.forEach(((value, key) => mapped.set(key, supplier(value, key)) ));
      return mapped;
  };
}
Nils Rösel answered 2019-10-09T08:17:44Z
0 votes

您可以使用map()数组,但Maps没有此类操作。 Axel Rauschmayer博士的解决方案:

  • 将地图转换为[key,value]对数组。
  • 映射或过滤数组。
  • 将结果转换回地图。

例:

let map0 = new Map([
  [1, "a"],
  [2, "b"],
  [3, "c"]
]);

const map1 = new Map(
  [...map0]
  .map(([k, v]) => [k * 2, '_' + v])
);

导致

{2 => '_a', 4 => '_b', 6 => '_c'}
Roman answered 2019-10-09T08:18:38Z
0 votes

您可以使用myMap.forEach,并在每个循环中使用map.set更改值。

myMap = new Map([
  ["a", 1],
  ["b", 2],
  ["c", 3]
]);

for (var [key, value] of myMap.entries()) {
  console.log(key + ' = ' + value);
}


myMap.forEach((value, key, map) => {
  map.set(key, value+1)
})

for (var [key, value] of myMap.entries()) {
  console.log(key + ' = ' + value);
}

hunterliu answered 2019-10-09T08:19:11Z
translate from https://stackoverflow.com:/questions/31084619/map-a-javascript-es6-map