简体   繁体   中英

How to return an array from a map?

I want to return 0, 1 or 2 images from a javascript-map, depending on how many there are.

  function images () {
    if (item.has('images')) {
      const response = [item.get('images').get(0)]
      if(item.get('images').has(100)){
        response.push(item.get('images').get(1))
      }
      return response
    } else {
      return []
    }
  }

This is how I currently do it. If I had an array of images, I could simply do

return arr.slice(0,2)

Could I do something similar with a map?

Yes! Map s are iterable and you can destructure iterables with ease:

const m = new Map([['a', 1], ['b', 2], ['c', 3]]);
const [head, next] = m.values();
console.log(head, next);

Specifically, I think the Map.prototype.values method will help you. It returns an iterable (although not necessarily an array) of values from the map.

Combine that with a little bit of logic:

function images (m) {
  if (m.has('images')) {
    const data = m.get('images'), values = data.values();
    if (data.size < 100) {
      const [head] = values;
      return [head];
    } else { 
      const [head, next] = values;
      return [head, next];
    }
  } else {
    return [];
  }
}

You may be able to clean up the repeated [foo, bar] = baz pattern, although I'm not sure the best way. Felix Kling's comment with Array.from and slice will certainly work, although it may be slow with large maps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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