简体   繁体   中英

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 average value of all exchange rate value.

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:

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);

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
  }
}

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/object-scan@18.1.2/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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM