【问题标题】:Property 'entries' does not exist on type ObjectConstructorObjectConstructor 类型上不存在属性“条目”
【发布时间】:2018-10-13 01:51:23
【问题描述】:

我正在使用 object.entries 方法将一些 JSON 对象数据推送到数组中......它正在工作,现在我收到错误:

“ObjectConstructor”类型上不存在属性“条目”。

我通过查看类似问题了解到,这可能是因为我使用的打字稿版本不支持条目方法,但是有替代方法吗?由于我是打字稿的新手,所以我对更改版本等感到不舒服。

Object.entries(data).forEach(([key, value]) => {
                this.array.push ({
                        id: key,
                        name: value.name,
                        desc: value.desc})
            });

感谢您的任何意见/帮助 :)

【问题讨论】:

    标签: javascript


    【解决方案1】:

    尝试将"esnext" 添加到tsconfig.json 文件中的libs,如下所示:

      "lib": ["es2018", "dom", "esnext"] 
    

    Typescript issue 30933

    【讨论】:

      【解决方案2】:

      也许您使用的浏览器不支持该新功能Object.entries

      您应该从mdn 安装以下“polyfill”

      if (!Object.entries)
        Object.entries = function( obj ){
          var ownProps = Object.keys( obj ),
              i = ownProps.length,
              resArray = new Array(i); // preallocate the Array
          while (i--)
            resArray[i] = [ownProps[i], obj[ownProps[i]]];
      
          return resArray;
        };
      

      运行该代码后,Object.entries 应该可用于您的 javascript 运行时,它应该修复错误


      另外,你可以用这种方式编写代码来给人一种不同的感觉

      // gather the items
      const items = Object.entries(data).map(([key, value]) => ({
        id: key,
        name: value.name,
        desc: value.desc
      }))
      
      // append items to array
      this.array = [...this.array, ...items]
      

      【讨论】:

      • 非常感谢这个作品!听起来很傻,但我以前没有听说过 polyfills。谢谢!
      猜你喜欢
      • 2018-01-07
      • 1970-01-01
      • 2019-02-17
      • 2016-06-27
      • 2020-10-02
      • 1970-01-01
      • 2018-11-13
      • 2016-12-16
      • 2021-01-09
      相关资源
      最近更新 更多