有没有办法将 JavaScript 对象转换为格式更清晰的另一个对象?

nic*_*kh3 2 javascript arrays rest object data-cleaning

当访问公共寄存器 API 时,我收到的信息超出了我的需要,有时返回的数据有微小的变化。我想删除一些不必要的字段,将嵌套字段移动到顶层,然后重命名它们。目标是标准化多个不同 API 的格式,并将内存需求保持在最低限度。下面的例子:

原始对象:

[
  {
    startDate: "2022/08/27",
    expiryDate: "2025/08/27",
    party: {
      type: "Business",
      name: "Irregular Expressions Inc."
    },
    location: {
      type: "Office",
      address: {
        locality: "Boston",
        postcode: "PE21 8QR"
      }
    }
  },
  {
    startDate: "2023/12/22",
    expiryDate: "2024/06/22",
    party: {
      type: "Charity",
      name: "Save the Badgers"
    },
    site: {
      type: "Office",
      address: {
        locality: "Badgerton",
        postcode: "BA6 6ER"
      }
    }
  },
]
Run Code Online (Sandbox Code Playgroud)

我想将其转换为更小、更干净的数组:

[
  {
    startDate: "2022/08/27",
    expiryDate: "2025/08/27",
    partyName: "Irregular Expressions Inc.",
    location: "Boston"
  },
  {
    startDate: "2023/12/22",
    expiryDate: "2024/06/22",
    partyName: "Save the Badgers",
    location: "Badgerton"
  },
]
Run Code Online (Sandbox Code Playgroud)

我已尝试以下操作,但出现错误。

module.exports = {
  testTransform: (inputArray) => {
    const outputArray = []
      
    inputArray.forEach(element => {
      outputArray.push({
        startDate: element.startDate,
        expiryDate: element.expiryDate,
        partyName: element.party.name,
        location: element.location.address.locality
      })
    })

    return JSON.stringify(outputArray, null, '  ')
  }
}
Run Code Online (Sandbox Code Playgroud)
TypeError: Cannot read properties of undefined (reading 'address')
Run Code Online (Sandbox Code Playgroud)

我的方向正确吗,或者有更简单的方法吗?我一直在寻找这种类型的转变,但没有成功——我错过了什么?

Nin*_*olz 6

您可以使用逻辑 OR来获取locationor ,然后使用可选链接运算符来获取属性。site||?.

const
    data = [{ startDate: "2022/08/27", expiryDate: "2025/08/27", party: { type: "Business", name: "Irregular Expressions Inc." }, location: { type: "Office", address: { locality: "Boston", postcode: "PE21 8QR" } } }, { startDate: "2023/12/22", expiryDate: "2024/06/22", party: { type: "Charity", name: "Save the Badgers" }, site: { type: "Office", address: { locality: "Badgerton", postcode: "BA6 6ER" } } }],
    result = data.map(o => ({
        startDate: o.startDate,
        expiryDate: o.expiryDate,
        partyName: o.party.name,
        location: (o.location || o.site)?.address?.locality
    }));

console.log(result);
Run Code Online (Sandbox Code Playgroud)