在访问公共寄存器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"
      }
    }
  },
]

我想将其转换为更小、更整洁的数组:

[
  {
    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"
  },
]

我已经try 了下面的方法,但我收到一个错误.

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, '  ')
  }
}
TypeError: Cannot read properties of undefined (reading 'address')

我是在朝着正确的方向前进,还是有一种更简单的方法来做到这一点?我一直在寻找这种类型的转变,但没有运气--我错过了什么?

推荐答案

你可以用logical OR ||表示locationsite,然后用optional chaining operator ?.表示属性.

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);

Javascript相关问答推荐

如何解决(不忽略)reaction详尽的linter规则,而不会在获取数据时导致无限的reender循环

在JavaScript中,如何将请求的回调函数的结果合并到运行的代码中?

使用useParams路由失败

用相器进行向内碰撞检测

在JavaScript中对大型级联数组进行切片的最有效方法?

浮动Div的淡出模糊效果

TypeScript索引签名模板限制

从Node JS将对象数组中的数据插入Postgres表

在使用HighChats时如何避免Datatables重新初始化错误?

Next.js服务器端组件请求,如何发送我的cookie token?

禁用.js文件扩展名并从目录导入隐式根index.js时,找不到NodeJS导入模块

Web Crypto API解密失败,RSA-OAEP

映射类型定义,其中值对应于键

如果一个字符串前面有点、空格或无字符串,后面有空格、连字符或无字符串,则匹配正则表达式

将基元传递给THEN处理程序

如何使用<;Link>;执行与JS Reaction中的";window.Location=/GameOverDied;";类似的操作?

使每个<;li>;元素的 colored颜色 与随机生成的 colored颜色 列表不同(不重复

是否可以在不更改组件标识的情况下换出Reaction组件定义(以维护状态/引用等)?如果是这样的话,是如何做到的呢?

JavaScript&;Reaction-如何避免在不使用字典/对象的情况下出现地狱?

在Java脚本中构建接口的对象