Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Kristian Woods
23,414 PointsHow do you add two separate object literal properties together?
I'm trying to combine the number properties of two separate object literals. But I don't know how to go about it
const booklist = [
{
bookName: "The Game",
bookPrice: 10
},
{
bookName: "48 Laws",
bookPrice: 20
}
];
for(let i = 0; i < booklist.length; i++) {
let price = booklist[i].bookPrice;
console.log(price) // outputs 10, 20
}
I want to add the 10 and 20 together and output the result. How do I go about that?
2 Answers
james south
Front End Web Development Techdegree Graduate 33,271 Pointsinstead of logging the price, you can add each one to a sum variable initialized at 0 outside the for loop. inside the loop you would have sum += price.
james south
Front End Web Development Techdegree Graduate 33,271 Pointsthere is also a method called reduce that can be used to add the numbers in an array.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
Kristian Woods
23,414 PointsKristian Woods
23,414 PointsHey, James, thanks! I knew it was something simple. I'll also look into that reduce method you mentioned. Thanks again