将对象推入数组

时间:2017-01-26 23:33:13

标签: javascript arrays object express

全部,我正在尝试将对象推送到数组和控制台。记录新数组以查看它的外观,并且看起来好像它无法正常工作。你能告诉我我做错了什么吗?

<% var testObjArray = [] %>    
<% var testObj = {} %>

<% currentUser.shares.forEach(function(share){ %>
    <% if(!share || share.length < 1){ %>
    <!--DO NOTHING-->
    <% } else { %>
        <% if(currentUser.id == share.yes_owner.id){ %>
            <% testObj.price = share.event.yes_purchase_price %>
            <% testObj.yes_or_no = "YES" %>

        <% } else { %>

            <% testObj.price = share.event.no_purchase_price %>
            <% testObj.yes_or_no = "No" %>
        <% }%>
            <% testObj.quantity = 1 %>
            <% testObj.eventId = share.event.id %>
            <% testObj.name = share.event.name %>

        <% testObjArray.push(testObj) %>
        <% console.log(testObj) %>
    <% }%>
<% }) %>
<% console.log("THIS IS THE NEW OBJARRAY: " + testObjArray) %>

我希望最终结果是并且期待它是......

[{ price: undefined,
  yes_or_no: 'No',
  quantity: 1,
  eventId: 588a107edf666e0273614cca,
  name: 'Will this work?' },
{...}, 
{...},
{ price: undefined,
  yes_or_no: 'No',
  quantity: 1,
  eventId: 588a107edf666e0273614cca,
  name: 'Will this work?' }
...]

然而,事实证明......

“这是新的OBJARRAY:”[对象],[对象],[对象],[对象]

3 个答案:

答案 0 :(得分:3)

更改此

console.log("THIS IS THE NEW OBJARRAY: " + testObjArray)

console.log("THIS IS THE NEW OBJARRAY: ", testObjArray)

因为"string" + Object将对象打印为字符串

答案 1 :(得分:1)

您正在注销对象引用,以便在对象上注销可以调用JSON.stringify()的对象键和值的字符串:

<% console.log("THIS IS THE NEW OBJARRAY: " + JSON.stringify(testObjArray)) %>

答案 2 :(得分:1)

您的console.log()导致对象隐式调用toString(),因为您正在使用字符串连接它。

您可以将n个参数传递给console.log(),以便更改

console.log("THIS IS THE NEW OBJARRAY: " + testObjArray)

console.log("THIS IS THE NEW OBJARRAY: ", testObjArray);

会为您提供您期望的输出。