diff --git a/README.md b/README.md index aae2b13..ded57fd 100644 --- a/README.md +++ b/README.md @@ -316,6 +316,11 @@ jsesc([ 'foo\x00bar', [1, '©', { 'foo': true, 'qux': null }], 42 ], { 'json': true }); // → '["foo\\u0000bar",[1,"\\u00A9",{"foo":true,"qux":null}],42]' +// Undefined object properties are skipped, similarily to `JSON.stringify()`: +jsesc({ foo: undefined, bar: null }, { + 'json': true +}); +// → '{"bar": null}' // Values that aren’t allowed in JSON are run through `JSON.stringify()`: jsesc([ undefined, -Infinity ], { 'json': true diff --git a/jsesc.js b/jsesc.js index 7b8b923..46b25a6 100644 --- a/jsesc.js +++ b/jsesc.js @@ -2,9 +2,11 @@ const object = {}; const hasOwnProperty = object.hasOwnProperty; -const forOwn = (object, callback) => { +const forOwn = (object, callback, noUndefined) => { for (const key in object) { - if (hasOwnProperty.call(object, key)) { + if (hasOwnProperty.call(object, key) && + (!noUndefined || (typeof object[key] !== 'undefined')) + ) { callback(key, object[key]); } } @@ -225,7 +227,7 @@ const jsesc = (argument, options) => { (compact ? '' : ' ') + jsesc(value, options) ); - }); + }, !!json); if (isEmpty) { return '{}'; } diff --git a/src/jsesc.js b/src/jsesc.js index d3eaff1..fe677b4 100644 --- a/src/jsesc.js +++ b/src/jsesc.js @@ -2,9 +2,11 @@ const object = {}; const hasOwnProperty = object.hasOwnProperty; -const forOwn = (object, callback) => { +const forOwn = (object, callback, noUndefined) => { for (const key in object) { - if (hasOwnProperty.call(object, key)) { + if (hasOwnProperty.call(object, key) && + (!noUndefined || (typeof object[key] !== 'undefined')) + ) { callback(key, object[key]); } } @@ -225,7 +227,7 @@ const jsesc = (argument, options) => { (compact ? '' : ' ') + jsesc(value, options) ); - }); + }, !!json); if (isEmpty) { return '{}'; }