Jason Chen Jason Chen - 1 month ago 5
Javascript Question

Pushing items to same array Javascript

I have the following array, which is not really how it should be.

"people": [
{"name": "Bob"},
{"occupation": "King"}

If I put this data in a table, the info goes along a diagonal line, and not along the same line, like a normal table.

This result is generated by my routing code here:

user.people.push({'name': body.name });
user.occupation.push({'occupation': body.occupation });

I have tried this:

for (i = 0; i < people.length; i){
user.people[i].push({'name': body.name });
user.occupation[i].push({'occupation': body.occupation});

But this stops my POST request from working.


This is done using Node. My schema in my user.js contains the following lines.

people: [{
name: String,
occupation: String

In addition, my ejs rendered table is like so:

<% for (var i = 0; i < user.people.length; i++) {%>
<td><%=user.people[i].name %></td>
<td><%=user.people[i].occupation %></td>
<% } %>

Essentially what I want my array to look like is:

people: [{
name: Bob,
occupation: King

So after testing, in my instance the solution turned out to be the following:

'name': body.name,
'occupation': body.occupation

which goes to show that ample info was provided to solve this issue.


When you are accessing occupation, you call it through people[i].occupation:

<td><%=user.people[i].occupation %></td>

You need to do the same when editing it, like so:

user.people[i].occupation.push({'occupation': body.occupation});

or something like it.


Actually, come to think of it

user.people[i].push({'occupation': body.occupation});

Should do the trick.

Sorry, it's a little late over here.