My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

How to make this example code shorter?

DK's photo
DK
·Nov 8, 2017

Hey! This might be a stupid question but I don't know how to do it 'cause I'm a JS beginner. The motto of coding is DRY (don't repeat yourself) so I don't want to repeat myself.

Here's a short example that I made. I want to do sth like this with more objects (one, two, three, four ...) and not just these 3. So I would repeat myself very often with the calculations if I do it like the example. I've read you could do it with a for loop but I don't know how to do it so I ask you. I need every output that is in the comments. Hope it's easy to understand. :)

const coolObject = {
  "one": {
    "number1": 1,
    "number2": 2
  },
  "two": {
    "number1": 3,
    "number2": 4
  },
  "three": {
    "number1": 5,
    "number2": 6
  }
}

// first number of every object
const coolOne1 = coolObject.one.number1; // 1
const coolTwo1 = coolObject.two.number1; // 3
const coolThree1 = coolObject.three.number1; // 5
// sum of them
const coolSum1 = coolOne1 + coolTwo1 + coolThree1; // 9

// second number of every object
const coolOne2 = coolObject.one.number2; // 2
const coolTwo2 = coolObject.two.number2; // 4
const coolThree2 = coolObject.three.number2; // 6
// sum of them
const coolSum2 = coolOne2 + coolTwo2 + coolThree2; // 12

// sum of every object
const oneSum = coolOne1 + coolOne2; // 3
const twoSum = coolTwo1 + coolTwo2; // 7
const threeSum = coolThree1 + coolThree2; // 11
// sum of all
const total = coolSum1 + coolSum2; // 21
// OR
const total = oneSum + twoSum + threeSum; // 21