首页 > 解决方案 > 如何过滤到仅查看所需属性的对象(js)

问题描述

我正在使用 SheetJS ( https://github.com/SheetJS/sheetjs ) 来使用来自 excel 表的信息。到目前为止,我得到的是一个以单元格名称为对象的对象,如下所示:

Sheet1 = {
  A1: {
    t: "s",
    v: "Jhon"
  },
  A2: {
    t: "s",
    v: "Doe"
  }
}

等等。现在我需要找到我想要的数字(取决于日期)只在单元格 B14 到 AF14 之间查找)并返回我在上一步中得到的单元格下方的七个单元格。对我来说最难的部分是只看对象 B14、C14.. AF14。

标签: javascriptexcel

解决方案


我很确定sheetjs能够检索某些单元格而不是整个网格,但我从未使用过它。

我会做什么:

const sheet = {
  A1: {
    t: "s",
    v: "Jhon"
  },
  A2: {
    t: "s",
    v: "Doe"
  }
}

const start = 'B'.charCodeAt(0)
const end = 'F'.charCodeAt(0)

const objs = {}

for (let i = start; i <= end; i += 1) {
  const key = String.fromCharCode(i) + '14'
  if (key in sheet) {
    objs[key] = sheet[key]
  }
}

此代码应返回表示 B14 和 F14 之间单元格的对象的对象。

你也可以这样做:

const sheet = {
  A1: {
    t: "s",
    v: "Jhon"
  },
  A2: {
    t: "s",
    v: "Doe"
  }
}

const array = Object.entries(sheet).filter(([key]) => key.match(/^[B-F]14$/))

这将为您提供过滤对象的数组。

如果你想要下面的 7 个单元格,只需进行第二个循环。


推荐阅读