I am having an api response displayed as below
{
"children": [
{
"_id": "61f29cfb23ff35136c98fdcc"
},
{
"_id": "61f2ab6123ff35136c996839"
},
{
"_id": "61f2ad1a23ff35136c998270"
}
],
"id": "61e2e09244d6583cdfead089"
}
This is the code for the response
exports.fetchCategoryChildren = async (req,res) => {
const category = await Category
.find({_id: req.params.id })
.select('children._id')
if (!category) return res.status(400).json('No category found');
return res.json(_.head(category));
But i want a respone like this
[
"_id": "61f29cfb23ff35136c98fdcc",
"_id": "61f2ab6123ff35136c996839",
"_id": "61f2ad1a23ff35136c998270"
],
Because i want to use the response in an $in operator which takes an array.
How can i achieve my desired result?
CodePudding user response:
The desired output you want is not a valid JavaScript. You can have array of objects or array of strings.
Here is a code that returns an array of the ids, so the output will be:
["61f29cfb23ff35136c98fdcc", "61f2ab6123ff35136c996839", "61f2ad1a23ff35136c998270"]
const res = {
"children": [
{
"_id": "61f29cfb23ff35136c98fdcc"
},
{
"_id": "61f2ab6123ff35136c996839"
},
{
"_id": "61f2ad1a23ff35136c998270"
}
],
"id": "61e2e09244d6583cdfead089"
}
const mapped = res.children.map(child => child._id)
console.log(mapped)
// ["61f29cfb23ff35136c98fdcc", "61f2ab6123ff35136c996839", "61f2ad1a23ff35136c998270"]