ObjectConstructor 类型上不存在属性“entries”

thx*_*elp 2 javascript

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

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

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

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

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

Cha*_*kal 5

也许您使用的浏览器不支持该新功能,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;
  };
Run Code Online (Sandbox Code Playgroud)

该代码运行后,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]
Run Code Online (Sandbox Code Playgroud)