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

标签 javascript ecmascript-6

我正在尝试编写一个函数来创建一个新的对象数组,为我提供从 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/

相关文章:

javascript - 这个代理总是在代理 : trap returned falsish for property 'set' but still runs perfectly otherwise? 上抛出 'main' 是有原因的吗

javascript - 将 Canvas 中的图像保存到本地存储

javascript - 在 HTML5 Canvas 中使用动画使表情符号眨眼

javascript - 在 HTML URL 中使用数组

javascript - 处理外部函数导入

javascript - 使用另一个对象的键从对象数组创建新数组

Javascript如何提交表单?

javascript - Electron 应用程序 : How to 'lock' a computer?

javascript - 如何理解 JS 领域

javascript - 如何检查数组中的字符串是否包含二维数组中的两个或多个字符串?