Iterating Over Nested Object in NodeJS

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 value of all exchange rate value and sum it up

69 thoughts on “Iterating Over Nested Object in NodeJS”

  1. 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
      }
    }
    
    Reply
  2. 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
    }
    

    Further reading:

    Reply

Leave a Comment