Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Property 'entries' does not exist on type ObjectConstructor

Tags:

javascript

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

like image 526
thx4help Avatar asked Dec 21 '25 09:12

thx4help


2 Answers

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]
like image 170
ChaseMoskal Avatar answered Dec 24 '25 00:12

ChaseMoskal


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

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

See Typescript issue 30933.

like image 27
Jonathan Avatar answered Dec 23 '25 23:12

Jonathan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!