javascript - 展平嵌套对象而不出现 TS 错误

标签 javascript typescript

我正在为我的公司制作一个编辑表单,我的团队中的某人决定更改 API 有效负载返回的格式,而没有咨询团队的其他成员,现在我们正在迎头 catch 。

由于我们必须将调用的 API 将值发布回数据库,因此没有为嵌套对象设置,因此我需要将其展平,以便可以操作这些值并提交它。

这是新的嵌套结构

    {
       "status": 1, 
       "data" : {
            "name": "Tank",
            "dimensions": "2.0 x 2.5 x 4.0"
       }
    }

我需要将其转换回这样的内容:

    {
       "status": 1, 
       "name": "Tank",
       "dimensions": "2.0 x 22.5 x 4.0"
    }

我在网上找到了多种解决方案,但它们都给了我相同的 TypeScript 错误

“for (... in ...) 语句必须使用 if 语句进行过滤”

我还看到很多人都将第一个元素的名称嵌入到其嵌套元素的 from 中,如下所示:

    {
       "status": 1, 
       "data.name": "Tank",
       "data.dimensions": "2.0 x 22.5 x 4.0"
    }

有人可以告诉我如何重写这个扁平化函数,它可以消除 TS 错误,并且不会将第一级元素的名称附加到其嵌套元素中,从而给我留下简单的单级对象吗?

这是我的展平函数:

const obj = values;

const flattenObj = (ob) => {
  // The object which contains the final result
  const result = {};
  // loop through the object "ob"
  for (const i in ob) {
      // We check the type of the i using typeof() function and recursively call the function again
      if ((typeof ob[i]) === 'object' && !Array.isArray(ob[i])) {
          const temp = flattenObj(ob[i]);
          for (const j in temp) {
              // Store temp in result
              result[i + '.' + j] = temp[j];
          }
      }
      // Else store ob[i] in result directly
      else {
          result[i] = ob[i];
      }
  }
  return result;
};

console.log(flattenObj(ob));

最佳答案

你可以改变

for (const i in ob) { .. }

for (const [i, obi] of Object.entries(ob)) { // use obi instead of ob[i] }

这样你就根本不会接触原型(prototype)的东西。

关于javascript - 展平嵌套对象而不出现 TS 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76854672/

相关文章:

javascript - 使用循环创建一个简单的 Sencha 组件

javascript - Gridview 排序后运行回调

javascript - 如何使用 typescript 和 react-chartjs-2 声明插件选项

javascript - 如何从异步调用返回响应?

javascript - 使用 Javascript 更改菜单中的类

javascript - 如何获取对象列表并创建列表中对象的特定属性的 JSON?

typescript - 在 Typescript 中实现没有名称的函数

typescript tsc --声明

backbone.js - 在 Typescript 中运行 BackboneJs 事件

javascript,反复查找DOM元素