Home > Back-end >  ejs print value of array from specific id
ejs print value of array from specific id

Time:12-10

I send an array of object called gudangs from my controller app.js like this

res.render('daftar-staff', {
            title: 'Daftar Staff',
            session: req.session,
            layout: 'layouts/main-layouts',
            gudangs
        })

Its successfully sent to the ejs view and I received

{ _id: new ObjectId("61a804c4059d1d90797c8ad0"), nama: 'gudang benowo', alamat: '', __v: 0 },{ _id: new ObjectId("61a804ecdfa6962a0162850f"), nama: 'gudang pakal', alamat: '', __v: 0 },{ _id: new ObjectId("61a86fb98b3cd7f948a388b7"), nama: 'gudang tandes', alamat: 'tandes no 19', isFull: 'true', __v: 0 },{ _id: new ObjectId("61a872c07cc01577ddf78b53"), nama: 'gudang kepatihan', alamat: '', isFull: 'true', __v: 0 },{ _id: new ObjectId("61a954eee3c45454070d4b10"), alamat: 'jalan benowo 13', __v: 0 },{ _id: new ObjectId("61a955954e757a01405e44b4"), alamat: 'jalan benowo 13', __v: 0 }

What i want is to print nama on specific gudang _id

Right now I can accomplish this by iterate through all gudangs array like this

<% gudangs.forEach((gudang,i) => { %>
<% if(gudang._id==='xxxx'){ %>
<%= gudang.nama %>
<% } %>
<% } %>

I wonder is there any simple way to do this?

CodePudding user response:

Using JS array filters

<%= gudangs.filter(({ _id })=> {return _id === 'XXX'})[0]['nama'] %>

gudangs = [{ _id: "61a804c4059d1d90797c8ad0", nama: 'gudang benowo', alamat: '', __v: 0 },{ _id: "61a804ecdfa6962a0162850f", nama: 'gudang pakal', alamat: '', __v: 0 },{ _id: "61a86fb98b3cd7f948a388b7", nama: 'gudang tandes', alamat: 'tandes no 19', isFull: 'true', __v: 0 },{ _id: "61a872c07cc01577ddf78b53", nama: 'gudang kepatihan', alamat: '', isFull: 'true', __v: 0 },{ _id: "61a954eee3c45454070d4b10", alamat: 'jalan benowo 13', __v: 0 },{ _id: "61a955954e757a01405e44b4", alamat: 'jalan benowo 13', __v: 0 }];

console.log(gudangs.filter(({ _id })=> {return _id === '61a804ecdfa6962a0162850f'})[0]['nama']);

This is a working snippet. Remember that ObjectId is not defined in frontend Javascript.

  • Related