我正在尝试编写一个函数来创建一个新的对象数组,为我提供从 from
到 to
指定参数的所有数据。
即
const data = [
{
timestamp: '2015-09-01T16:00:00.000Z',
temperature: 27.1,
dewPoint: 17.1,
},
{
timestamp: '2015-09-01T16:10:00.000Z',
temperature: 27.2,
dewPoint: 17.2,
},
{
timestamp: '2015-09-01T16:20:00.000Z',
temperature: 27.3,
dewPoint: 17.3,
},
{
timestamp: '2015-09-01T16:30:00.000Z',
temperature: 27.4,
dewPoint: 17.4,
}
]
想法是有一个辅助方法来过滤和输出 from
和 to
中的数据到新数组 []
function getValuesInRange(from, to) {
let sortedArray = []
let filteredValues = []
let index = indexOf(from) // error => indexOf is not defined
while (index < sortedArray.length) {
const valueAtIndex = sortedArray[index]
if (valueAtIndex.key >= from && valueAtIndex.key < to) {
filteredValues.push(valueAtIndex.value)
index++
} else {
break
}
}
console.log(filteredValues)
return filteredValues
}
const fromDateTime = data[0].timestamp)
const toDateTime = data[2].timestamp)
getValuesInRange(fromDateTime, toDateTime)
由于
indexOf 未定义
,上述方法当前出错
在
getValuesInRange()
上,我是否相应地处理数据以在此处产生所需的结果?您能否也向我展示与此工作等效的 ES6?
最佳答案
您可以使用 .getTime()
和 filter()
尝试以下方式
The
getTime()
method returns the number of milliseconds since since the Unix Epoch
const data = [
{
timestamp: '2015-09-01T16:00:00.000Z',
temperature: 27.1,
dewPoint: 17.1,
},
{
timestamp: '2015-09-01T16:10:00.000Z',
temperature: 27.2,
dewPoint: 17.2,
},
{
timestamp: '2015-09-01T16:20:00.000Z',
temperature: 27.3,
dewPoint: 17.3,
},
{
timestamp: '2015-09-01T16:30:00.000Z',
temperature: 27.4,
dewPoint: 17.4,
}
]
function getData(arr,from,to){
from = new Date(from).getTime();
to = new Date(to).getTime();
return arr.filter(obj => {
let ms = new Date(obj.timestamp).getTime();
return ms < to && ms > from
})
}
console.log(getData(data,'2015-09-01T16:00:00.000Z','2015-09-01T16:30:00.000Z'))
关于JavaScript |获取对象内的数据范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55074188/