0

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?

2
  • 1
    If _.head(category) returns the referenced object, _.head(category).children.map({_id} => _id) will return the ID array. Commented Jan 29, 2022 at 13:43
  • The desired response could be EITHER: [ { "_id" : "61f29cfb23ff35136c98fdcc" }, { "_id": "61f2ab6123ff35136c996839" }, { "_id": "61f2ad1a23ff35136c998270" } ], OR it could be: [ "61f29cfb23ff35136c98fdcc", "61f2ab6123ff35136c996839", "61f2ad1a23ff35136c998270" ]. Please edit & update the question. Commented Jan 29, 2022 at 13:47

1 Answer 1

1

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"]

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.