Reputation: 123
I have the following code in the template of my component:
<th scope="row">{{@order.id}}</th>
<td>Name: {{@order.customer_name}}
</td>
<td>Delivery address: {{@order.address}}
Products in order: {{@order.products}}
Items: {{items}}
<td>{{@order.total_price}}$</td>
</tr>
And I have my computed property which should return and render each product name in the array of objects returned from the database:
items: computed('order.products', function() {
let products = this.get('order.products');
products.forEach(product => {
for(let i=0; i<products.length; i++){
return console.log(products[i].name);
}
});
}),
And when I run the following everything works okay and the names are displayed in the console like this:
Cheese on toast
3 Pizza
2 Macaroons bowl
But when I try to remove console.log and just return products[i].name, nothing seems to be returned. Am I missing something or trying to render it on my page incorrectly?
Upvotes: 1
Views: 107
Reputation: 1610
From the snippet, I'm presuming you want to return only the name of the products from the items
computed property. If so, then there is some issue here is with the handling of loops and not with the actual computed property.
So in your case, you can use map to filter out only the name of the product from the products array.
items: computed('order.products', function() {
let products = this.get('order.products');
let productNames = products.map((product) => {
return product.name;
});
return productNames;
})
Also, the computed property only retain the value that was returned from the definition. Thus you need to return the value explicitly as shown in the above snippet (return productNames
).
Upvotes: 4