0

How do I iterate over a dynamic nested object

{
  "2021-02-01": {
    "INR": 88.345,
    "CZK": 25.975,
    "JPY": 126.77
  },
  "2021-02-02": {
    "INR": 87.906,
    "CZK": 25.9,
    "JPY": 126.46
  },
  "2021-02-05": {
    "INR": 87.367,
    "CZK": 25.806,
    "JPY": 126.72
  }
}

Note: currency is dynamic it can change to other currency like here it is "INR, CZK, JPY" it can change to "USD, EUR, INR"

I need to get the value of all exchange rate of all currency in object and sum up all of them

here is what i have code (it is incomplete and i'm stuck in it)

      let rates = {here is object mentioned above}
     
      //iterating over object and pushing into array rateList
      for(let keys in rates){
            rateList.push(rates[keys])
      }
      
      //iterating over rateList array to get value
      rateList.forEach((obj)=>{
          console.log(Object.keys(obj)) //by this code i'm getting keys but how do i get value and sum it up
      })

Overall the objective is to get the average value of all exchange rate value.

4 Answers 4

2

Updated answer

Based on OP's comment below, there's still a shorthand-ish way to accomplish the requirement:

const rates = {
  "2021-02-01": {
    "INR": 88.345,
    "CZK": 25.975,
    "JPY": 126.77
  },
  "2021-02-02": {
    "INR": 87.906,
    "CZK": 25.9,
    "JPY": 126.46
  },
  "2021-02-05": {
    "INR": 87.367,
    "CZK": 25.806,
    "JPY": 126.72
  }
};

var returnObject = {};

Object.values(rates).forEach(childObject => { // loop all child objects within parent `rates` object:
    for (const [key, value] of Object.entries(childObject)) // extract each key=>value pair
      returnObject[key] = typeof returnObject[key] === 'undefined' ? value : returnObject[key] + value; // track it in `returnObject` - checks if the currency code already exists as a key in returnObject - if so, sums the current value and all previously-encountered values - if it doesn't already exist as a key in returnObject, sets the key to the current value
});

console.dir(returnObject);

Original answer

A shorthand-ish way of doing this would be:

const rates = {
  "2021-02-01": {
    "INR": 88.345,
    "CZK": 25.975,
    "JPY": 126.77
  },
  "2021-02-02": {
    "INR": 87.906,
    "CZK": 25.9,
    "JPY": 126.46
  },
  "2021-02-05": {
    "INR": 87.367,
    "CZK": 25.806,
    "JPY": 126.72
  }
};

for (var key of Object.keys(rates)) { // loop all dates in parent `rates` object:
    rates[key] = Object.values(rates[key]).reduce((acc, cv) => acc += cv); // extract the values for all keys in the child Object into an Array, then use reduce() to sum the values; finally, replace the initial child object with the float result of the summation
}
console.dir(rates);

Further reading:

Sign up to request clarification or add additional context in comments.

3 Comments

thanks for your response @esqew, I think I made mistake in my question. I need to sum up a particular currency like the sum of INR for a given date range your solution is doing sum of inr+czk+jpy but i need to find sum of 2021-02-05 {inr: 82} + 2021-02-04 {inr: 82} + 2021-02-03 {inr: 82} likewise to other currency
@MohammadYunus That makes sense, please edit your question to reflect & explain this better. I've updated my answer to reflect this new requirement.
I'll update my question, just one thing after sum up how can i get average of each? thanks @esqew
1

just try

let rates = {
  "2021-02-01": {
    "INR": 88.345,
    "CZK": 25.975,
    "JPY": 126.77
  },
  "2021-02-02": {
    "INR": 87.906,
    "CZK": 25.9,
    "JPY": 126.46
  },
  "2021-02-05": {
    "INR": 87.367,
    "CZK": 25.806,
    "JPY": 126.72
  }
}
let rateList = {};
let avarage = {}
//iterating over object and pushing into array rateList
for(let keys in rates){   
   Object.keys(rates[keys]).forEach((name , index)=>{
     if(rateList[name]){
    
      rateList[name]["avg"]  = (rateList[name]["avg"] + Object.values(rates[keys])[index] )/2
      rateList[name]["sum"]  += Object.values(rates[keys])[index]

     }
     else{
      let obj = {}
      obj.name = name;
      obj.sum =  Object.values(rates[keys])[index];
      obj.avg = Object.values(rates[keys])[index];
      rateList[name] = obj
     }
   }) 
}
rateList = Object.values(rateList)
console.log(rateList);

Comments

0
let rates = {here is object mentioned above};//main object

var keys = Object.keys(rates);// Will return ["2021-02-01", "2021-02-02"]

for(let i = 0; i < keys.length;i++){
  var obj = rates[keys[i]];//will return nested object. {"INR": 88.345,"CZK": 25.975,"JPY": 126.77
  }
}

Comments

0

Here is an iterative solution using object-scan

.as-console-wrapper {max-height: 100% !important; top: 0}
<script type="module">
import objectScan from 'https://cdn.jsdelivr.net/npm/[email protected]/lib/index.min.js';

const data = { '2021-02-01': { INR: 88.345, CZK: 25.975, JPY: 126.77 }, '2021-02-02': { INR: 87.906, CZK: 25.9, JPY: 126.46 }, '2021-02-05': { INR: 87.367, CZK: 25.806, JPY: 126.72 } };

const aggregate = objectScan(['*.*'], {
  rtn: 'context',
  beforeFn: (state) => {
    // eslint-disable-next-line no-param-reassign
    state.context = {};
  },
  filterFn: ({ property, value, context }) => {
    if (!(property in context)) {
      context[property] = 0;
    }
    context[property] += value;
  }
});

console.log(aggregate(data));
// => { JPY: 379.95, CZK: 77.68100000000001, INR: 263.61800000000005 }
</script>

Disclaimer: I'm the author of object-scan

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.