繁体   English   中英

如何在javascript中的json响应上使用map函数?

[英]How to use map function on a json response in javascript?

我正在使用 zomato API 在一个区域内查找随机餐厅。 这是 API 调用。

app.post('/locations/:query', async (req, res) => 
{
  try{
  const query = req.params.query;
  const data = await zomato.cities({ q: query,count: 1 })
  const cityId= await (data[0].id);
  const result = [];
  const nrOfRequests = 60; 
  let currCount = 0;  
  const nrOfEntries = 20;
  for(let i=0; i < nrOfRequests ; i++) {
    const response = await zomato.search({ entity_id: cityId, entity_type: 'city', start:currCount, count:nrOfEntries, sort:'rating', order:'desc' });
    result.push(...response.restaurants);
    currCount += nrOfEntries;
  }    
  const no = Math.floor(Math.random() * 60);     
  const restaur = result[no].restaurants.map(r => {
    return {
      name: r.name,
      url: r.url,
      location: r.location,
      price: r.price_range,
      thumbnail: r.thumb,
      rating: r.user_rating.aggregate_rating,
    }
  })
  res.send({restaur});
} catch (err) {
  console.error(err)
  res.status(500).send('error')
} 
});

这个 API 正在做的是

1)找到查询的cityId。(查询是一个城市名称)

2) 使用 for 循环根据评级查找该城市最多 60 家餐厅并将其推送到results[] 。(zomato api 限制每次调用只能显示 20 家餐厅)

3) 在 0 到 60 之间选择一个随机数,并从result输出该特定餐厅。

4)然后我想做的是找到名称价格等功能并返回在前端显示。

使用此代码我收到以下错误

TypeError: Cannot read property 'map' of undefined

result[no]响应如下所示。

{
  R: {
    has_menu_status: { delivery: -1, takeaway: -1 },
    res_id: 302578,
    is_grocery_store: false
  },
  apikey: '*************',
  id: '302578',
  name: 'Barbeque Nation',
  url: 'https://www.zomato.com/ncr/barbeque-nation-saket-new-delhi?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1',
  location: {
    address: 'M/A 04, DLF Avenue, District Centre, Saket, New Delhi',
    locality: 'DLF Avenue, Saket',
    city: 'New Delhi',
    city_id: 1,
    latitude: '28.5273432339',
    longitude: '77.2173847631',
    zipcode: '',
    country_id: 1,
    locality_verbose: 'DLF Avenue, Saket, New Delhi'
  },
  switch_to_order_menu: 0,
  cuisines: 'North Indian, BBQ, Beverages',
  timings: '12noon – 3:30pm, 6pm – 11pm (Mon-Sun)',
  average_cost_for_two: 1600,
  price_range: 3,
  currency: 'Rs.',
  highlights: [
    'Lunch',
    'Serves Alcohol',
    'Mall Parking',
    'Cash',
    'Credit Card',
    'Debit Card',
    'Dinner',
    'Takeaway Available',
    'Fullbar',
    'Indoor Seating',
    'Air Conditioned',
    'Reopened',
    'Buffet'
  ],
  offers: [],
  opentable_support: 0,
  is_zomato_book_res: 0,
  mezzo_provider: 'OTHER',
  is_book_form_web_view: 0,
  book_form_web_view_url: '',
  book_again_url: '',
  thumb: 'https://b.zmtcdn.com/data/pictures/chains/2/1212/b6429ddad24625e65344caabb921bd57.jpg?fit=around%7C200%3A200&crop=200%3A200%3B%2A%2C%2A',
  user_rating: {
    aggregate_rating: '4.7',
    rating_text: 'Excellent',
    rating_color: '3F7E00',
    rating_obj: { title: [Object], bg_color: [Object] },
    votes: 2248
  },
  all_reviews_count: 1159,
  photos_url: 'https://www.zomato.com/ncr/barbeque-nation-saket-new-delhi/photos?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1#tabtop',
  photo_count: 1991,
  menu_url: 'https://www.zomato.com/ncr/barbeque-nation-saket-new-delhi/menu?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1&openSwipeBox=menu&showMinimal=1#tabtop',
  featured_image: 'https://b.zmtcdn.com/data/pictures/chains/2/1212/b6429ddad24625e65344caabb921bd57.jpg',
  medio_provider: 1,
  has_online_delivery: 1,
  is_delivering_now: 0,
  store_type: '',
  include_bogo_offers: true,
  deeplink: 'zomato://restaurant/302578',
  is_table_reservation_supported: 1,
  has_table_booking: 0,
  events_url: 'https://www.zomato.com/ncr/barbeque-nation-saket-new-delhi/events#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1',
  phone_numbers: '080 61756005',
  all_reviews: { reviews: [ [Object], [Object], [Object], [Object], [Object] ] },
  establishment: [ 'Casual Dining' ],
  establishment_types: []
}

您显示的results[no]确实没有名为restaurants属性。 您有一个名为results的数组,您要从该数组中选择一个元素。 当您只有一个元素时,就没有什么可“映射”的了。

相反,只需从该元素返回您想要的字段:

const no = Math.floor(Math.random() * 60);     
const restaur = {
  name: result[no].name,
  url: result[no].url,
  location: result[no].location,
  price: result[no].price_range,
  thumbnail: result[no].thumb,
  rating: result[no].user_rating.aggregate_rating,
};
res.send(restaur);

暂无
暂无

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

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