Home > Software design >  How to pluck out field value from arrays of object
How to pluck out field value from arrays of object

Time:01-03

I am retrieving data from mongoose database using node.js and express.

Currently, I am getting a response like this

[
    {
        "images": [
            {
                "link": "https://just-incase-from-a-far/yop.png"
            },
            {
                "link": "https://main-link-test/lol.png"
            }
        ]
    },
    {
        "images": [
            {
                "link": "https://example-link/happy.jpg"
            },
            {
                "link": "https://example-link/angry.jpg"
            },
            {
                "link": "https://example-link/sad.png"
            }
        ]
    }
]

But I want a response like this

[
    "https://just-incase-from-a-far/yop.png",
    "https://main-link-test/lol.png",
    "https://example-link/happy.jpg",
    "https://example-link/angry.jpg",
    "https://example-link/sad.png"
]

How can I achieve my desired response.

This is my code that gives me my response of array objects

exports.getProducts = async (req,res) => {
    const result = await Product
    .find({isEmpty:false})
    .select("-_id -createdAt -__v -isEmpty")
    .exec()
    if(!result) return res.status(400).json({ data: 'No product found' });
    if(result.err) return res.json({ err: err });
    return res.json(result);

}

CodePudding user response:

Just add a outer loop extracting the links

links = [];
result.forEach((obj) => {
    links = [...obj.images.map((o) => o.link), ...links];
})
  • Related