Reputation: 5808
I have this part of code:
var dependencies:any = npmPackage.versions[version].dependencies;
dependencies = Object.entries(dependencies).map( ([name, version]) => {
console.log(name,typeof(version));
return {
name,
version.replace(/[^\w\s]/gi, ''),
}
});
it should turn this:
{
"loose-envify": "^1.1.0",
"object-assign": "^4.1.1",
"prop-types": "^15.6.2"
}
to this:
[
{
name: "loose-envify",
version: "^1.1.0"
},
{
name: "object-assign",
version: "^4.1.1"
},
{
same here...
}
]
I am tring to remove the chars like ~ ! ^
from the version variable (instead ^4.1.1
=> 4.1.1
), I keep getting the error:
',' expected.
for the version.replace(/[^\w\s]/gi, ''),
part.
I'm guessing it's due to the typescript. I don't think this should cause any problem.. when having the return version variable only as version
it works without this error.
I'm kinda new to typescript so I'd be happy to understand why rather than just getting the answer ;)
Upvotes: 0
Views: 102
Reputation: 10790
You need to specify a property name :
return {
name,
version : version.replace(/[^\w\s]/gi, ''), // <-- here a property name required
}
And the error you are getting is not related to typescript. Here javascript can't determine the property name (like most of the languages that provide similar functionality.) because of a function call. It should be a variable. The feature you use is called object property value shorthand. Here some examples :
const foo = 1 ;
const bar = {c: "baz"};
const shortHand = { foo,bar}; // foo and bar property names
const fail = { foo,bar.c}; // here property name can't be infered.
const fail2 = {bar, foo.toString()} // here property name can't be infered.
And for the regex I would suggest a pattern like :
/^[\^!~]/gi
Upvotes: 1
Reputation: 12108
Your code, with a slight modification to add a property name, works at runtime, so the problem is due to TypeScript. My advice: remove the TypeScript, or, use a new variable and type it correctly. I'll show the latter in a comment here:
let dependencies = {
"loose-envify": "^1.1.0",
"object-assign": "^4.1.1",
"prop-types": "^15.6.2"
};
const nameVersionDeps /* : { name: string; version: string; }[] */ = Object.entries(dependencies).map(([name, version]) => {
return {
name,
version: version.replace(/[^\w\s]/gi, ''),
}
});
console.log(nameVersionDeps)
Upvotes: 2
Reputation: 2021
I'm not exactly sure what you are trying to do, but this code should do the conversion part:
startingObject = {
"loose-envify": "^1.1.0",
"object-assign": "^4.1.1",
"prop-types": "^15.6.2"
}
Object.entries(startingObject).map(entry => ({ name: entry[0], value: entry[1] }))
Will produce:
[
{
name: "loose-envify",
version: "^1.1.0"
},
{
name: "object-assign",
version: "^4.1.1"
},
{
name: "prop-types",
version: "^15.6.2"
}
]
Upvotes: 0
Reputation: 313
I think you need to remove the trailing comma of your line here:
version.replace(/[^\w\s]/gi, ''),
and if you want to remove ~ ! ^
then use this regex: /[~!^]/gi
Upvotes: 0