Seeking advice how to process this nested JSON/Object

91 views Asked by At

I have a nested JSON and want to end up with the result array, how is this possible? Any tips on how i can accomplish this? Do i need to use a nester for in/of loop? Higher order functions etc? I am new to nested objects, any tip or good reference will be appreaciated!

// const db shows the desired result once db.save() is called. I want it to include the Date, Symbols (USD etc.) and the value of it - all wrapped inside their own object

const db = [
{ Date: '1999-01-05', AUD: 1.8944, SEK: 9.4025, USD: 1.179 },
{ Date: '1999-01-06', AUD: 1.882, SEK: 9.305, USD: 1.1743 },

];

// the json that i recieve upon fetching

const json = {
rates: {
    '1999-01-08': {
        AUD: 1.8406,
        SEK: 9.165,
        USD: 1.1659,
    },
    '1999-01-06': {
        AUD: 1.882,
        SEK: 9.305,
        USD: 1.1743,
    },
    '1999-01-07': {
        AUD: 1.8474,
        SEK: 9.18,
        USD: 1.1632,
    },
    '1999-01-05': {
        AUD: 1.8944,
        SEK: 9.4025,
        USD: 1.179,
    },
},
start_at: '1999-01-05',
base: 'EUR',
end_at: '1999-01-10',

};

2

There are 2 answers

0
Y0ss-Please On

Here's a solution using nested for loops and Object.entires to get a key/value pair from your object. It creates an array of objects just like your desired result. (Not in the exact order, as Javascript doesn't care for keeping objects sorted).

function save(data) {
    const db = []
    
    for (const [key, value] of Object.entries(data.rates)) {
        rate = { 'Date': key }
        for (const [_key, _value] of Object.entries(value)) {
            rate[_key] = _value
        }
        db.push(rate)
    }
    return db
}

Usage; in your posted example, would be:

db = save(json)
0
APV On

Thanks for the answer, i didn't get it to work as i probably messed something up or explained poorly, apologise. But seeing you using nested for loop helped me figure out this approach which resulted in every currency and exchange rate from a specific date to be in one object with only key values.

        const db = [];
    for (const prop in json.rates) {
      Object.keys(json.rates[prop]).forEach((element) => {
        const obj = {
          date: prop,
          symbol: element,
          rate: json.rates[prop][element],
          base: json.base,
        };
        db.push(obj);
      });
    }
    console.log(db);

enter code here

enter code here