JS map nested props and string to number

Need help please to change/map this data objects structure from This:

var a = JSON.parse(JSON.stringify({"Meta Data": {"1. Information": "Daily Prices (open, high, low, close) and Volumes", "2. Symbol": "AAA", "3. Last Refreshed": "2019-10-25", "4. Output Size": "Full size", "5. Time Zone": "US/Eastern"}, "Time Series (Daily)": {"2019-10-25": {"1. open": "10.7500", "2. high": "11.8100", "3. low": "10.6600", "4. close": "11.7900", "5. volume": "6453477"}, "2019-10-24": {"1. open": "10.7200", "2. high": "10.8050", "3. low": "10.5200", "4. close": "10.6000", "5. volume": "2223747"}}}))

Into looking This:

var b = [{ time: '2019-10-25', open: 10.7500, high: 11.8100, low: 10.6600, close: 11.7900 },{ time: '2019-10-24', open: 10.7200, high: 10.8050, low: 10.5200, close: 10.6000 }]

I am not sure what I need a map or loop that goes into the nested structure to make the new object; where the time keys become values with new key called time ; and also where the open/high/low/close values are no longer string; and the object within the array is flattened as in the desired view.

I have hundreds of thousands of entries so please let me know the fastest/best/easiest way to accomplish this. Thank you.

Answer

You can use Object.entries and Object.fromEntries to switch between array/object structures. The inner keys needs to get the number prefix dropped, so for that you can use split, slice or a more versatile regular expression.

var a = {"Meta Data": {"1. Information": "Daily Prices (open, high, low, close) and Volumes","2. Symbol": "AAA","3. Last Refreshed": "2019-10-25","4. Output Size": "Full size","5. Time Zone": "US/Eastern"},"Time Series (Daily)": {"2019-10-25": {"1. open": "10.7500","2. high": "11.8100","3. low": "10.6600","4. close": "11.7900","5. volume": "6453477"},"2019-10-24": {"1. open": "10.7200","2. high": "10.8050","3. low": "10.5200","4. close": "10.6000","5. volume": "2223747"}}};

let result = Object.entries(a["Time Series (Daily)"]).map(([time, obj]) =>
    ({ time, ...Object.fromEntries(Object.entries(obj).map(([key, value]) =>
        [key.replace(/^[d. ]+/, ""), isNaN(value) ? value : +value]
    ))})
);
    
console.log(result);

Leave a Reply

Your email address will not be published. Required fields are marked *