gpt4 book ai didi

JavaScript |获取对象内的数据范围

转载 作者:行者123 更新时间:2023-11-30 11:07:28 25 4
gpt4 key购买 nike

我正在尝试编写一个函数来创建一个新的对象数组,为我提供从 fromto 指定参数的所有数据。

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

想法是有一个辅助方法来过滤和输出 fromto 中的数据到新数组 []

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com