使用array.map()函数在javascript中将对象作为数组

时间:2017-07-25 20:31:55

标签: javascript node.js

使用array.map函数时,我在对象中获取了一些数据。但是,我需要在数组中获取它。图像功能出现问题。

EBIT:

我的部分涉及array.map函数的代码如下所示(对不起,如果代码看起来很困惑,考虑到手头的问题,但是由于我之前遗漏了其余的代码,似乎有些混乱):

function getVenues(page, size, venues) {
  page = page || 0;
  size = size || 200;
  venues = venues || [];
  return axios
    .get(`https://app.ticketmaster.com/discovery/v2/venues.json?apikey=MYAPIKEY&page=${page}&size=${size}&countryCode=DK`)
    .then(response => response.data._embedded.venues)
    .then(rawVenues => {
      rawVenues.forEach(venue => venues.push(venue));
      if (rawVenues.length < size) {
        // All done return the compiled list.
        return venues;
      }
      // Recurse over the next set of venues by adding another promise to the chain.
      return getVenues(page + 1, size, venues);
    });
}

function getEvents(page, size, events) {
  page = page || 0;
  size = size || 200;
  events = events || [];
  return axios
    .get(`https://app.ticketmaster.com/discovery/v2/events.json?apikey=MYAPIKEY&countryCode=DK&size=${size}&page=${page}`)
    .then(response => response.data._embedded.events)
    .then(rawEvents => {
      rawEvents.forEach(event => events.push(event));
      if (rawEvents.length < size) {
        // All done return the compiled list.
        return events;
      }
      // Recurse over the next set of events by adding another promise to the chain.
      return getEvents(page + 1, size, events);
    });

}

app.get('/tm2', (req, res) => {
  getVenues().then(rawVenues => {

    const venuesToBeInserted = rawVenues.map(venue => {
      return {
        sourceID: venue.id,
        venue: venue.name,
        postalCode: venue.postalCode,
        city: venue.city.name,
        country: venue.country.name,
        countryCode: venue.country.countryCode,
        address: !!venue.address ? venue.address.line1 : null,
        longitude: !!venue.location ? venue.location.longitude : null,
        latitude: !!venue.location ? venue.location.latitude : null,
        source: 'ticketmaster'
      };
    });

    // Return promise so errors bubble up the chain...
    return Venue.create(venuesToBeInserted).then(venues => {
      console.log("venues inserted");



      // Return promise so errors bubble up the chain...
      return getEvents().then(rawEvents => {

        const eventsToBeInserted = rawEvents.map(event => {
          return {
            name: event.name.trim(),
            slug: slugify(event.name.trim()).toLowerCase(),
            sourceID: !!event._embedded.venues ? event._embedded.venues.map(sourceIDs => {
              return {
                sourceID: !!sourceIDs ? sourceIDs.id : []
              }
            }) : [],
            tags: !!event.classifications ? event.classifications.map(tag => {
              return {
                tags: !!tag ? [tag.segment.name, tag.genre.name] : [],
              }
            }) : [],
            images: !!event.images ? event.images.map(image => {
              return {
                images: !!image ? image.url : []
              }
            }) : []

          }
        })

        // Return promise so errors bubble up the chain...
        return Event.create(eventsToBeInserted).then(events => {
          console.log("events inserted");

        });
      });
    });
  }).then(() => { // This then is fired after all of the promises above have resolved...
    return Event.find({}).select({
      genres: 1,
      tag: 1
    }).limit(30).populate('event').populate('venue').then(events => {
      console.log(util.inspect(events));
      res.send(events);
    });
  }).catch(err => { // Catches any error during execution.
    console.error(err);
    res.status(500).send(err);
  });
});

我目前的输出如下:

images: 
   [ { images: 'url_1' },
     { images: 'url_2' },
     { images: 'url_3' } ] 

我希望以下列格式获取它:

images: 
   [ { 'url_1' },
     { 'url_2' },
     { 'url_3' } ] 

1 个答案:

答案 0 :(得分:0)

我会避免进一步评论如何更好地组织代码。现在,要获得所需的结果,只需删除已将每次调用包裹到map()的对象文字。例如,修复images,改为:

images: !!event.images ? event.images.map(image => {
  return {
    images: !!image ? image.url : []
  }
}) : []

到此:

images: !!event.images ? event.images.map(image => {
  return !!image ? image.url : ''
}).filter(Boolean) : []

我不确定为什么您的输入event.images数组会包含没有url属性的格式错误的对象,或者会遗漏自己,但.filter(Boolean)通过删除任何内容来解决这些问题。空字符串,在三元运算符... ? ... : ''的第三个表达式中指定。