JS 将嵌套的道具和字符串映射到数字

JS map nested props and string to number

需要帮助change/map 这个数据对象结构来自这个:

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

看这个:

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

我不确定我需要什么映射或循环进入嵌套结构来创建新对象;时间键成为具有名为 time 的新键的值;还有 open/high/low/close 值不再是字符串的地方;并且数组中的对象在所需视图中被展平。

我有数十万个条目,所以请告诉我 fastest/best/easiest 完成此操作的方法。谢谢。

您可以使用Object.entriesObject.fromEntries在array/object结构之间切换。内部键需要删除数字前缀,因此您可以使用 splitslice 或更通用的正则表达式。

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