2

I'm using the object.entries method to push some JSON object data into an array... it was working and now I'm getting the error:

Property 'entries' does not exist on type 'ObjectConstructor'.

I understand from looking at similar issues, this may be because the version of typescript I am using does not support the entries method, but is there an alternative? I don't feel comfortable changing versions etc as I'm new to typescript.

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

thank you for any input/help :)

thx4help
  • 35
  • 1
  • 3

3 Answers3

5

maybe you're using a browser that doesn't support that new-ish function, Object.entries

you should install the following "polyfill" from mdn:

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

after that code is run, Object.entries should be made available to your javascript runtime, it should fix the error


also, you could write your code this way to give a different sort of feel

// 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]
ChaseMoskal
  • 7,151
  • 5
  • 37
  • 50
3

Try adding "esnext" to the libs in your tsconfig.json file, like this:

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

See Typescript issue 30933.

Jonathan
  • 32,202
  • 38
  • 137
  • 208
0

Try adding "esnext" to the libs in your tsconfig.json file, like this:

 "lib": ["ES2017"]

restart your vscode & make it take effect

maybe you also meet error

Cannot find name 'setTimeout' | 'console' | 'localStorage'.

you can add "DOM" & "ESNext", and it will be

"lib": ["ES2017", "DOM", "ESNext"],
van sun
  • 66
  • 1
  • 4