[英]Selecting the first “n” dates with jQuery
我从这样的API得到响应
{
"Meta Data": {
"1. Information": "Daily Time Series with Splits and Dividend Events",
"2. Symbol": "NSE:TECHM",
"3. Last Refreshed": "2019-09-06",
"4. Output Size": "Full size",
"5. Time Zone": "US/Eastern"
},
"Time Series (Daily)": {
"2019-09-06": {
"1. open": "716.3500"
},
"2019-09-05": {
"1. open": "710.0000"
},
"2019-09-04": {
"1. open": "705.0000"
},
"2019-09-03": {
"1. open": "698.0000"
},
"2019-08-30": {
"1. open": "693.0000"
}
}
}
我需要从响应的“时间序列(每日)”部分获取前3个日期。 .slice(0,3)无效,因为它包含日期。
不能保证对象中键的顺序。因此, first three
是相对术语。 您可以使用Object.keys
从"Time Series (Daily)"
对象中获取键,并对其进行迭代以获取值
let data = { "Meta Data": { "1. Information": "Daily Time Series with Splits and Dividend Events", "2. Symbol": "NSE:TECHM", "3. Last Refreshed": "2019-09-06", "4. Output Size": "Full size", "5. Time Zone": "US/Eastern" }, "Time Series (Daily)": { "2019-09-06": { "1. open": "716.3500" }, "2019-09-05": { "1. open": "710.0000" }, "2019-09-04": { "1. open": "705.0000" }, "2019-09-03": { "1. open": "698.0000" }, "2019-08-30": { "1. open": "693.0000" } } } let newData = Object.keys(data["Time Series (Daily)"]); for (let x = 0; x <= 2; x++) { console.log(data["Time Series (Daily)"][newData[x]]) }
由于不能保证对象中键的顺序,因此可以使用Object.entries()
获取存储在键"Time Series (Daily)"
中的对象条目。 然后,您可以根据日期以降序对该数组进行.sort()
,使其按降序排列,然后使用.slice(0, n)
从数组中获取前n
项目。 最后,您可以将所有这些内容封装在Object.fromEntries()
,这将从条目数组中构建一个对象:
const data = { "Meta Data": { "1. Information": "Daily Time Series with Splits and Dividend Events", "2. Symbol": "NSE:TECHM", "3. Last Refreshed": "2019-09-06", "4. Output Size": "Full size", "5. Time Zone": "US/Eastern" }, "Time Series (Daily)": { "2019-09-06": { "1. open": "716.3500" }, "2019-09-05": { "1. open": "710.0000" }, "2019-09-04": { "1. open": "705.0000" }, "2019-09-03": { "1. open": "698.0000" }, "2019-08-30": { "1. open": "693.0000" } } } const get_dates = (obj, n) => Object.fromEntries(Object.entries(obj["Time Series (Daily)"]) .sort(([a], [b]) => new Date(b) - new Date(a)) .slice(0, n)); const res = get_dates(data, 3); console.log(res);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.