๐ชข JavaScript
Comments in JSON¶
TL;DR: JSON is data-only. If you include a comment, then it must be data too.
{
"//": "This is a comment",
"key": "value"
}
Conditional array/object content¶
const foo = [
"bar",
...(truty ? ["baz"] : []),
...(falsy ? ["qux"] : []),
];
["bar", "baz"]
const foo = {
bar: "bar",
...(truthy && { baz: 'baz' }),
...(falsy && { qux: 'qux' }),
};
{"bar": "bar", "baz": "baz"}
Map object entries¶
const mapObject = (obj, fn) => Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, fn(v)]));
JSON stringify object values
mapObject({key: {foo: "bar"}}, (v) => JSON.stringify(v));
{key: '{"foo":"bar"}'}
Named capturing group regex¶
const semver = /^(?<major>\d+)(?:\.(?<minor>\d+)(?:\.(?<patch>\d+))?)?(?:-(?<label>.+))?$/;
const result = "1.2.3-alpha".match(semver);
result.groups.major; // '1'
result.groups.minor; // '2'
result.groups.patch; // '3'
result.groups.label; // 'alpha'
Optional chaining operator¶
// The old way
val result = (obj || {}).data;
// The new way
val result = obj?.data;