[英]How to use JSON response as an array in javascript
Here is my response I get from API request:这是我从 API 请求中得到的回复:
[ 'bookShelf3', 'bookShelf4', 'bookShelf5' ]
Here is a part of my code which searches through my mongoDB Databese:这是我的代码的一部分,它通过我的 mongoDB 数据库进行搜索:
const responseToSearchC = (req, res) => {
console.log(req.body.searchTerm);
db.collection('subtitle')
.find({
series: { $in: ['bookShelf1'] },
$text: { $search: req.body.searchTerm },
})
I just want to make my code dynamic and instead hard coding ['bookShelf1'] set its value by JSON response.我只想使我的代码动态化,而不是硬编码 ['bookShelf1'] 通过 JSON 响应设置其值。 the problem is the response from API is an object (although it is look like an array) and I cannot replace it with my hard codded array ['bookShelf1']
问题是 API 的响应是 object (虽然它看起来像一个数组),我不能用我的硬编码数组替换它 ['bookShelf1']
I tried to stringify it but it didn't work cuz its a string again, and not an array like hardcoded one我试图对它进行字符串化,但它没有工作,因为它又是一个字符串,而不是像硬编码那样的数组
If the response is really an object like:如果响应确实是 object,例如:
{ 0: 'bookShelf3', 1:'bookShelf4', 2: 'bookShelf5'}
you can simply utilize the Object.values() method which returns all of the object's values as an array.您可以简单地利用Object.values()方法将所有对象的值作为数组返回。
Here's an example:这是一个例子:
let ob={ 0: 'bookShelf3', 1:'bookShelf4', 2: 'bookShelf5'}; console.log(Object.values(ob));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.