The Mozilla docs say to return undefined (instead of "none"):

http://jsfiddle.net/userdude/rZ5Px/

function replacer(key,value)
{
    if (key=="privateProperty1") return undefined;
    else if (key=="privateProperty2") return undefined;
    else return value;
}

var x = {
    x:0,
    y:0,
    divID:"xyz",
    privateProperty1: 'foo',
    privateProperty2: 'bar'
};

alert(JSON.stringify(x, replacer));

Here is a duplication method, in case you decide to go that route (as per your comment).

http://jsfiddle.net/userdude/644sJ/

function omitKeys(obj, keys)
{
    var dup = {};
    for (var key in obj) {
        if (keys.indexOf(key) == -1) {
            dup[key] = obj[key];
        }
    }
    return dup;
}

var x = {
    x:0,
    y:0,
    divID:"xyz",
    privateProperty1: 'foo',
    privateProperty2: 'bar'
};

alert(JSON.stringify(omitKeys(x, ['privateProperty1','privateProperty2'])));

EDIT - I changed the function key in the bottom function to keep it from being confusing.

Answer from Jared Farrish on Stack Overflow
๐ŸŒ
Melvin George
melvingeorge.me โ€บ blog โ€บ hide-remove-omit-certain-values-keys-from-json-stringify-output-javascript
How to hide, remove or omit certain values or keys from the JSON.stringify() method's output in JavaScript? | MELVIN GEORGE
June 13, 2021 - // a simple object const personDetails = { name: "John Doe", age: 23, pin: 686612, mob: 9445678654, }; // Stringify personDetails object // using JSON.stringify() method const personDeatilsStr = JSON.stringify(personDetails, (key, value) => { // Check if key matches the string "pin" or "mob" // if matched return value "undefined" if (key === "pin" || key === "mob") { return undefined; } // else return the value itself return value; }); console.log(personDeatilsStr); /* OUTPUT ------ { "name":"John Doe", "age":23 } */ Now if we look at the output, we can see that the key pin and mob are removed from the output string.
Discussions

how to remove json object key and value.? - javascript
I have a json object as shown below. where i want to delete the "otherIndustry" entry and its value by using below code which doesn't worked. var updatedjsonobj = delete myjsonobj['otherIndustry']... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Typescript JSON.stringify, remove key property name
The following JSON Stringify is not working. I just realized my API Request should look like this without a Key, for api to execute correctly. More on stackoverflow.com
๐ŸŒ stackoverflow.com
How to remove nested JSON.stringify() properties
I'm trying to modify a string with Typescript. The string is created by the JSON.stringify() method. I want to remove the properties "id", "lightStatus" and the "value" attributes of "inputPort" and "outputPort". More on stackoverflow.com
๐ŸŒ stackoverflow.com
April 1, 2017
how to remove json object key and value.?
I have a json object as shown below. where i want to delete the "otherIndustry" entry and its value by using below code which doesn't worked. var updatedjsonobj = delete myjsonobj['otherIndustry']... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
DEV Community
dev.to โ€บ alwarg โ€บ purging-unwanted-properties-in-js-object-45ol
Purging unwanted properties in js object - DEV Community
June 10, 2020 - We are using replacer function from the JSON.stringify method for removing the empty properties. What? Are you sure?๐Ÿคท๐Ÿปโ€โ™‚๏ธ ยท yes. Let me explain ยท let stringfiedObj = JSON.stringify(obj, (key, value) => { return ['', null].includes(value) || (typeof value === 'object' &&(value.length === 0 || Object.keys(value).length === 0)) ?
Top answer
1 of 7
128

delete operator is used to remove an object property.

delete operator does not returns the new object, only returns a boolean: true or false.

In the other hand, after interpreter executes var updatedjsonobj = delete myjsonobj['otherIndustry']; , updatedjsonobj variable will store a boolean value.

How to remove Json object specific key and its value ?

You just need to know the property name in order to delete it from the object's properties.

delete myjsonobj['otherIndustry'];

let myjsonobj = {
  "employeeid": "160915848",
  "firstName": "tet",
  "lastName": "test",
  "email": "[email protected]",
  "country": "Brasil",
  "currentIndustry": "aaaaaaaaaaaaa",
  "otherIndustry": "aaaaaaaaaaaaa",
  "currentOrganization": "test",
  "salary": "1234567"
}
delete myjsonobj['otherIndustry'];
console.log(myjsonobj);

If you want to remove a key when you know the value you can use Object.keys function which returns an array of a given object's own enumerable properties.

let value="test";
let myjsonobj = {
      "employeeid": "160915848",
      "firstName": "tet",
      "lastName": "test",
      "email": "[email protected]",
      "country": "Brasil",
      "currentIndustry": "aaaaaaaaaaaaa",
      "otherIndustry": "aaaaaaaaaaaaa",
      "currentOrganization": "test",
      "salary": "1234567"
}
Object.keys(myjsonobj).forEach(function(key){
  if (myjsonobj[key] === value) {
    delete myjsonobj[key];
  }
});
console.log(myjsonobj);

2 of 7
22

There are several ways to do this, lets see them one by one:

  1. delete method: The most common way

const myObject = {
    "employeeid": "160915848",
    "firstName": "tet",
    "lastName": "test",
    "email": "[email protected]",
    "country": "Brasil",
    "currentIndustry": "aaaaaaaaaaaaa",
    "otherIndustry": "aaaaaaaaaaaaa",
    "currentOrganization": "test",
    "salary": "1234567"
};

delete myObject['currentIndustry'];
// OR delete myObject.currentIndustry;
  
console.log(myObject);

  1. By making key value undefined: Alternate & a faster way:

let myObject = {
    "employeeid": "160915848",
    "firstName": "tet",
    "lastName": "test",
    "email": "[email protected]",
    "country": "Brasil",
    "currentIndustry": "aaaaaaaaaaaaa",
    "otherIndustry": "aaaaaaaaaaaaa",
    "currentOrganization": "test",
    "salary": "1234567"
  };

myObject.currentIndustry = undefined;
myObject = JSON.parse(JSON.stringify(myObject));

console.log(myObject);

  1. With es6 spread Operator:

const myObject = {
    "employeeid": "160915848",
    "firstName": "tet",
    "lastName": "test",
    "email": "[email protected]",
    "country": "Brasil",
    "currentIndustry": "aaaaaaaaaaaaa",
    "otherIndustry": "aaaaaaaaaaaaa",
    "currentOrganization": "test",
    "salary": "1234567"
};


const {currentIndustry, ...filteredObject} = myObject;
console.log(filteredObject);

Or if you can use omit() of underscore js library:

const filteredObject = _.omit(currentIndustry, 'myObject');
console.log(filteredObject);

When to use what??

If you don't wanna create a new filtered object, simply go for either option 1 or 2. Make sure you define your object with let while going with the second option as we are overriding the values. Or else you can use any of them.

hope this helps :)

๐ŸŒ
Pluralsight
pluralsight.com โ€บ blog โ€บ tech guides & tutorials
Delete Data from JSON Using a Key in React | Pluralsight
November 9, 2020 - The delete operator can be used to remove a key-value pair from a JavaScript object: delete jsonObj.name; /* after delete { age: 10, phone: ["1234567890", "1234567890"] } */ Alternately, string keys can be used to delete a key-value pair: let ...
๐ŸŒ
MDN Web Docs
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Web โ€บ JavaScript โ€บ Reference โ€บ Global_Objects โ€บ JSON โ€บ stringify
JSON.stringify() - JavaScript - MDN Web Docs
As an array, its elements indicate the names of the properties in the object that should be included in the resulting JSON string. Only string and number values are taken into account; symbol keys are ignored. As a function, it takes two parameters: the key and the value being stringified.
Find elsewhere
๐ŸŒ
Dyn-web
dyn-web.com โ€บ tutorials โ€บ php-js โ€บ json โ€บ filter.php
Using a Replacer or Filter with JSON.stringify
February 3, 2015 - Next we will explore how a replacer ... to JSON.stringify to screen and modify the results. A replacer function accepts two arguments: name and value. The name and value of each object property or array element is passed to the replacer function in turn.[2] The replacer function can use the name or value as a means of modifying the property value or removing it from the ...
๐ŸŒ
Muffin Man
muffinman.io โ€บ blog โ€บ json-stringify-removes-undefined
JSON.stringify removes undefined, how to keep it ยท Muffin Man
October 1, 2018 - const user = { name: 'Stanko', phone: undefined }; const replacer = (key, value) => typeof value === 'undefined' ? null : value; const stringified = JSON.stringify(user, replacer); // -> "{\"name\":\"Stanko\",\"phone\":null}"
Top answer
1 of 7
129

delete operator is used to remove an object property.

delete operator does not returns the new object, only returns a boolean: true or false.

In the other hand, after interpreter executes var updatedjsonobj = delete myjsonobj['otherIndustry']; , updatedjsonobj variable will store a boolean value.

How to remove Json object specific key and its value ?

You just need to know the property name in order to delete it from the object's properties.

delete myjsonobj['otherIndustry'];

let myjsonobj = {
  "employeeid": "160915848",
  "firstName": "tet",
  "lastName": "test",
  "email": "test@email.com",
  "country": "Brasil",
  "currentIndustry": "aaaaaaaaaaaaa",
  "otherIndustry": "aaaaaaaaaaaaa",
  "currentOrganization": "test",
  "salary": "1234567"
}
delete myjsonobj['otherIndustry'];
console.log(myjsonobj);

If you want to remove a key when you know the value you can use Object.keys function which returns an array of a given object's own enumerable properties.

let value="test";
let myjsonobj = {
      "employeeid": "160915848",
      "firstName": "tet",
      "lastName": "test",
      "email": "test@email.com",
      "country": "Brasil",
      "currentIndustry": "aaaaaaaaaaaaa",
      "otherIndustry": "aaaaaaaaaaaaa",
      "currentOrganization": "test",
      "salary": "1234567"
}
Object.keys(myjsonobj).forEach(function(key){
  if (myjsonobj[key] === value) {
    delete myjsonobj[key];
  }
});
console.log(myjsonobj);

2 of 7
22

There are several ways to do this, lets see them one by one:

  1. delete method: The most common way

const myObject = {
    "employeeid": "160915848",
    "firstName": "tet",
    "lastName": "test",
    "email": "test@email.com",
    "country": "Brasil",
    "currentIndustry": "aaaaaaaaaaaaa",
    "otherIndustry": "aaaaaaaaaaaaa",
    "currentOrganization": "test",
    "salary": "1234567"
};

delete myObject['currentIndustry'];
// OR delete myObject.currentIndustry;
  
console.log(myObject);

  1. By making key value undefined: Alternate & a faster way:

let myObject = {
    "employeeid": "160915848",
    "firstName": "tet",
    "lastName": "test",
    "email": "test@email.com",
    "country": "Brasil",
    "currentIndustry": "aaaaaaaaaaaaa",
    "otherIndustry": "aaaaaaaaaaaaa",
    "currentOrganization": "test",
    "salary": "1234567"
  };

myObject.currentIndustry = undefined;
myObject = JSON.parse(JSON.stringify(myObject));

console.log(myObject);

  1. With es6 spread Operator:

const myObject = {
    "employeeid": "160915848",
    "firstName": "tet",
    "lastName": "test",
    "email": "test@email.com",
    "country": "Brasil",
    "currentIndustry": "aaaaaaaaaaaaa",
    "otherIndustry": "aaaaaaaaaaaaa",
    "currentOrganization": "test",
    "salary": "1234567"
};


const {currentIndustry, ...filteredObject} = myObject;
console.log(filteredObject);

Or if you can use omit() of underscore js library:

const filteredObject = _.omit(currentIndustry, 'myObject');
console.log(filteredObject);

When to use what??

If you don't wanna create a new filtered object, simply go for either option 1 or 2. Make sure you define your object with let while going with the second option as we are overriding the values. Or else you can use any of them.

hope this helps :)

๐ŸŒ
Execute Program
executeprogram.com โ€บ courses โ€บ modern-javascript โ€บ lessons โ€บ customizing-json-serialization
Modern JavaScript: Customizing JSON Serialization
At each step, our replacer function can do three things: Return the value argument unmodified, which won't change the stringified object. Return some other value, which will replace the original value in the stringified JSON. Return undefined, which ...
Top answer
1 of 16
179

This simple regular expression solution works to unquote JSON property names in most cases:

const object = { name: 'John Smith' };
const json = JSON.stringify(object);  // {"name":"John Smith"}
console.log(json);
const unquoted = json.replace(/"([^"]+)":/g, '$1:');
console.log(unquoted);  // {name:"John Smith"}

Extreme case:

var json = '{ "name": "J\\":ohn Smith" }'
json.replace(/\\"/g,"\uFFFF");  // U+ FFFF
json = json.replace(/"([^"]+)":/g, '$1:').replace(/\uFFFF/g, '\\\"');
// '{ name: "J\":ohn Smith" }'

Special thanks to Rob W for fixing it.

Limitations

In normal cases the aforementioned regexp will work, but mathematically it is impossible to describe the JSON format with a regular expression such that it will work in every single cases (counting the same number of curly brackets is impossible with regexp.) Therefore, I have create a new function to remove quotes by formally parsing the JSON string via native function and reserialize it:

function stringify(obj_from_json) {
    if (typeof obj_from_json !== "object" || Array.isArray(obj_from_json)){
        // not an object, stringify using native function
        return JSON.stringify(obj_from_json);
    }
    // Implements recursive object serialization according to JSON spec
    // but without quotes around the keys.
    let props = Object
        .keys(obj_from_json)
        .map(key => `${key}:${stringify(obj_from_json[key])}`)
        .join(",");
    return `{${props}}`;
}

Example: https://jsfiddle.net/DerekL/mssybp3k/

2 of 16
34

It looks like this is a simple Object toString method that you are looking for.

In Node.js this is solved by using the util object and calling util.inspect(yourObject). This will give you all that you want. follow this link for more options including depth of the application of method. http://nodejs.org/api/util.html#util_util_inspect_object_options

So, what you are looking for is basically an object inspector not a JSON converter. JSON format specifies that all properties must be enclosed in double quotes. Hence there will not be JSON converters to do what you want as that is simply not a JSON format.Specs here: https://developer.mozilla.org/en-US/docs/Using_native_JSON

Object to string or inspection is what you need depending on the language of your server.

๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ javascript-remove-a-json-attribute
JavaScript | Remove a JSON attribute | GeeksforGeeks
August 11, 2023 - let myObj = { 'prop_1': { 'prop_11': 'value_11', 'prop_12': 'value_12' } }; function removeJsonAttr() { delete myObj.prop_1.prop_11; console.log(JSON.stringify(myObj)); } removeJsonAttr(); ... The task is to add a JSON attribute to the JSON object. To do so, Here are a few of the most used techniques discussed.Example 1: This example adds a prop_11 attribute to the myObj object via var key.
๐ŸŒ
Muffinman
muffinman.io โ€บ json-stringify-removes-undefined
JSON.stringify removes undefined, how to keep it - Muffin Man
October 1, 2018 - You will be automatically redirected to https://muffinman.io/blog/json-stringify-removes-undefined/.
๐ŸŒ
W3Schools
w3schools.com โ€บ jsref โ€บ jsref_stringify.asp
JavaScript JSON stringify() Method
drop() every() filter() find() flatMap() forEach() from() map() reduce() some() take() JS JSON ยท parse() stringify() JS Maps ยท new Map clear() delete() entries() forEach() get() groupBy() has() keys() set() size values() JS Math ยท
๐ŸŒ
Sentry
sentry.io โ€บ sentry answers โ€บ javascript โ€บ removing properties from objects in javascript
Removing Properties from Objects in JavaScript | Sentry
You have an object with several properties and you want to remove some of these properties before using the object further. let person = { firstName: "John", lastName: "Doe", gender: "Male", age: 34 }; const json = JSON.stringify(person); console.log(json); // => {"firstName":"John","lastName":"Doe","gender":"Male","age":34} // What can we do if we don't want the `age` property in the JSON string?
Top answer
1 of 3
2

It sounds like you are looking for a data-serialization format that is human-readable and version-control-friendly but not as strict about quotes as JSON.

Such formats include:

  • Relaxed JSON (RJSON) (simple keys and simple values generally do not require quotes)
  • Hjson (simple keys and simple values generally do not require quotes)
  • YAML (keys and values generally do not require quotes)
  • JavaScript object literal (also printed out by many implementations of "console.dir()" when passed a JavaScript object; simple keys generally not required to be quoted, but string values must be quoted by either single quotes or double quotes)

for completeness:

JSON (requires double-quotes around keys, also called property names, and requires double-quotes around string data values).

2 of 3
1

Yes, it is possible to remove the quotes from the keys. Doing so will render it invalid as JSON, but still valid when used directly in JavaScript code, only if the keys you use are also valid variable names. When you paste a JSON object in JavaScript code, it may be useful to have the quotes removed, as they can in some cases take up a lot of data. If that's relevant to your project, then this is the answer for you.

The function below works for any JavaScript variable and works fine with objects/arrays containing objects/arrays. I've added comments to explain what's going on. Please note that this code does not check for possible reserved keywords that may not be allowed as JavaScript keys, such as "for".

function toUnquotedJSON(param){ // Implemented by Frostbolt Games 2022
    if(Array.isArray(param)){ // In case of an array, recursively call our function on each element.
        let results = [];
        for(let elem of param){
            results.push(toUnquotedJSON(elem));
        }
        return "[" + results.join(",") + "]";
    }
    else if(typeof param === "object"){ // In case of an object, loop over its keys and only add quotes around keys that aren't valid JavaScript variable names. Recursively call our function on each value.
        let props = Object
            .keys(param)
            .map(function(key){
                // A valid JavaScript variable name starts with a dollar sign (?), underscore (_) or letter (a-zA-Z), followed by zero or more dollar signs, underscores or alphanumeric (a-zA-Z\d) characters.
                if(key.match(/^[a-zA-Z_$][a-zA-Z\d_$]*$/) === null) // If the key isn't a valid JavaScript variable name, we need to add quotes.
                    return `"${key}":${toUnquotedJSON(param[key])}`;
                else
                    return `${key}:${toUnquotedJSON(param[key])}`;
            })
            .join(",");
        return `{${props}}`;
    }
    else{ // For every other value, simply use the native JSON.stringify() function.
        return JSON.stringify(param);
    }
}