How to use Object.values with typescript?
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.
Object.values()
is part of ES2017, and the compile error you are getting is because you need to configure TS to use the ES2017 library. You are probably using ES6 or ES5 library in your current TS configuration.
Solution: use es2017
or es2017.object
in your --lib
compiler option.
For example, using tsconfig.json
:
"compilerOptions": {
"lib": ["es2017", "dom"]
}
Note that targeting ES2017 with TypeScript does not emit polyfills in the browser for ES2017 (meaning the above solves your compile error, but you can still encounter a runtime error because the browser doesn't implement ES2017 Object.values
), it's up to you to polyfill your project code yourself if you want. And since Object.values
is not yet well supported by all browsers (at the time of this writing) you definitely want a polyfill: core-js
will do the job.
I have increased target in my tsconfig.json
to enable this feature in TypeScript
{
"compilerOptions": {
"target": "es2017",
......
}
}
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);