How to use Object.values with typescript?

2020-02-02 08:33发布

I am trying to form a comma separated string from an object,

const data = {"Ticket-1.pdf":"8e6e8255-a6e9-4626-9606-4cd255055f71.pdf","Ticket-2.pdf":"106c3613-d976-4331-ab0c-d581576e7ca1.pdf"};
const values = Object.values(data).map(x => x.substr(0, x.length - 4));
const commaJoinedValues = values.join(',');
console.log(commaJoinedValues);

How to do this with TypeScript?

getting an error file:

severity: 'Error'
message: 'Property 'values' does not exist on type 'ObjectConstructor'.'
at: '216,27'
source: 'ts'

9条回答
聊天终结者
2楼-- · 2020-02-02 08:44

You can use Object.values in TypeScript by doing this (<any>Object).values(data) if for some reason you can't update to ES7 in tsconfig.

查看更多
一纸荒年 Trace。
3楼-- · 2020-02-02 08:44

I just hit this exact issue with Angular 6 using the CLI and workspaces to create a library using ng g library foo.

In my case the issue was in the tsconfig.lib.json in the library folder which did not have es2017 included in the lib section.

Anyone stumbling across this issue with Angular 6 you just need to ensure that you update you tsconfig.lib.json as well as your application tsconfig.json

查看更多
放荡不羁爱自由
4楼-- · 2020-02-02 08:47

Having my tslint rules configuration here always replacing the line Object["values"](myObject) with Object.values(myObject).

Two options if you have same issue:

(Object as any).values(myObject)

or

/*tslint:disable:no-string-literal*/
`Object["values"](myObject)`
查看更多
等我变得足够好
5楼-- · 2020-02-02 08:47

Even simpler, use _.values from underscore.js https://underscorejs.org/#values

查看更多
家丑人穷心不美
6楼-- · 2020-02-02 08:49

Simplest way is to cast the Object to any, like this:

const data = {"Ticket-1.pdf":"8e6e8255-a6e9-4626-9606-4cd255055f71.pdf","Ticket-2.pdf":"106c3613-d976-4331-ab0c-d581576e7ca1.pdf"};
const obj = <any>Object;
const values = obj.values(data).map(x => x.substr(0, x.length - 4));
const commaJoinedValues = values.join(',');
console.log(commaJoinedValues);

And voila – no compilation errors ;)

查看更多
贪生不怕死
7楼-- · 2020-02-02 08:52

using Object.keys instead.

const data = {
  a: "first",
  b: "second",
};

const values = Object.keys(data).map(key => data[key]);

const commaJoinedValues = values.join(",");
console.log(commaJoinedValues);
查看更多
登录 后发表回答