首页 > 解决方案 > 如何组合两个json响应并作为一个整体发送?

问题描述

我正在使用 zomato API,它在一次 api 调用中只发送 20 个名称,我想要至少 60 个响应,所以我想调用同一个 api 三次并将所有响应组合在一起。

app.get('/locations/:query', async (req, res) => {
  const query = req.params.query;
  const data = await zomato.cities({ q: query,count: 1 })
  const cityId= await (data[0].id);
  const restaurants1 = await zomato.search({ entity_id: cityId, entity_type: 'city', start:0, count:20, sort:'rating', order:'desc' })
  const restaurants2 = await zomato.search({ entity_id: cityId, entity_type: 'city', start:20, count:40, sort:'rating', order:'desc' })
  const restaurants =  Object.assign(restaurants1,...restaurants2);
  res.send(restaurants);
  
})

到目前为止,我只尝试了 40 岁,但即使这样也行不通。如果有另一个常量restaurant3,开始 40 和结束 60,我如何合并这三个并将它们发回?

标签: javascriptnode.jsexpress

解决方案


你不应该restaurants2在你的Object.assign(). 使用以下方法之一:

const restaurants = Object.assign(restaurants1, restaurants2);

// or

const restaurants = { ...restaurants1, ...restaurants2 };

推荐阅读