简体   繁体   中英

Can't get a specific property of js object

I am working with ejs, mongodb and express. In ejs file, I have set value of an Edit button to the the js object passed into the ejs file so that I can query required data after in express after the Edit button makes a post request to a route. EJS edit button code:

<% listOfRecords.forEach((singleRecord)=>{ %>
        <div class="card card-body">
            <form method="post">
                    <button formaction="/edit" class="btn btn-success btn-sm" name="editBtn" value="<%=singleRecord%>">Edit</button>            
            </form>
        </div>  
    <% }); %> 

However, I am able console log the js object by the following code in express:

app.post('/edit', (req, res)=>{
    console.log(req.body.editBtn);
});

The output of the above code is:

{
  _id: 60605148a1fba61fd8f2446f,
  title: 'asdf',
  author: 'sadf',
  class_section: 'asfd',
  dateIssued: 2021-03-01T00:00:00.000Z,
  __v: 0
}

But when I try doing this: console.log(req.body.editBtn.title); it shows the error, undefined

What am I doing wrong in this?

I don't think we have enough information. The code from my perspective looks fine. It should work.

What you could try doing is getting the attribute by doing console.log(req.body.editBtn['title']); instead of console.log(req.body.editBtn.title); .

You could also try destructuring the title: const { title } = req.body.editBtn .

Although these should theoretically not work? Maybe something else in your code is wrong ?

Edit:

If req.body.editBtn is a string then try JSON.parse(req.body.editBtn); then get the attribute you want.

The real problem was that req.body.editBtn was in String format. So to make this work, change in EJS file would be:

<button formaction="/edit" class="btn btn-success btn-sm" name="editBtn" value="<%=JSON.stringify(singleRecord)%>">Edit</button>

This shall convert js object into a string properly and then in express file, the change is:

let editBtn = req.body.editBtn;
let info = JSON.parse(editBtn);

Now I can access any property of the object because it was converted to and from string properly.

you should get attributes from JSON.parse method's output, rather than req.body.editBtn which is still string.

app.post('/edit', (req, res)=>{
    const data = JSON.parse(req.body.editBtn);
    // console.log(req.body.editBtn);
    console.log(data.title);
    console.log(data.author);
    // ....
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM