Given input valid JSON JSON.parse() or JSON.stringify() replacer function can be utilized to substitute "undefined" for null.
``` const convertJSONNullToUndefined = json => Object.assign({} // if input is valid JSON string omit JSON.stringify(), use JSON.parse() with same replacer function // e.g., JSON.parse(`{"x":null,"y":null,"z":null}`, (key, value) => value === null ? `${void 0}` : value) , ...Object.entries(JSON.parse(JSON.stringify(json, (key, value) => value === null ? `${void 0}` : value))) .map(([key, value]) => value === `${void 0}` ? {[key]: void value} : value )); // {x: "undefined", y: "undefined", z: "undefined"} const {z = "a"} = convertJSONNullToUndefined({ x: null, y:null, z: null }); // "a" assigned to z ``` Alternatively RegExp can be used to replace JSON string values ``` const convertJSONNullToUndefined = json => Object.assign({}, ...function*() { // negative lookahead to match ":" followed by null followed by comma or closing curly bracket character // replace null with "undefined" const o = JSON.parse(JSON.stringify(json).replace(/(?![:])null(?=[,}])/g, `"${void 0}"`)); for (const key in o) {yield {[key]: void o[key]}} }()); // {x: "undefined", y: "undefined", z: "undefined"} const {z = "a"} = convertJSONNullToUndefined({ x: null, y:null, z: null }); // "a" assigned to z ``` On Thu, May 2, 2019 at 8:23 AM Cyril Auburtin <cyril.aubur...@gmail.com> wrote: > Similarly to > > ```js > const { x = 'a' } = {}; // z === 'a' > const { y = 'a' } = { y: undefined }; // z === 'a' > const { z = 'a' } = { z: null }; // z === null > ``` > I'd like to propose > > ```js > const { x =? 'a' } = {}; // z === 'a' > const { y =? 'a' } = { y: undefined }; // z === 'a' > const { z =? 'a' } = { z: null }; // z === 'a' > ``` > Which would handle also null values in default cases > > This is because default destructuring introduced in ES6 doesn't handle > null values, null values in JSON are quite common from APIs, it'd be > convenient > > It's also inspired by the null-coalescing operator > https://github.com/tc39/proposal-nullish-coalescing > _______________________________________________ > es-discuss mailing list > es-discuss@mozilla.org > https://mail.mozilla.org/listinfo/es-discuss >
_______________________________________________ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss