I have the following javascript object and want to stringify in JSON format.
I want to skip the (key, value)
pair at the specific level. In my case, I don’t want to encode user.id
but want to stringify package.id
.
I am using the replacer
of JSON.stringify
. I know the replacer function gets every key/value pair including nested objects and array items. It is applied recursively. but I need to know is there any other way around instead of creating a new object
let student = {
id: 1, // want to skip this id.
name: 'John',
age: 30,
isAdmin: false,
courses: ['html', 'css', 'js'],
package: {
id: 121, // but need this id.
name: "starter",
price: 15
},
spouse: null
};
let str = JSON.stringify(student, function(key, value) {
return key == 'id' ? undefined : value
});
console.log(str);
3
Answers
this
in thereplacer
function ofJSON.stringify
will hold the original object it’s called for:So you could check if any of the top-level keys exist in that object, for example, I’ve choisen
age
as astudent
has one, but thepackage
doesn’t.Of course this is reversable, you could also ‘only remove the key if the object has (eg) a
price
key’:return !("price in this) && ...
You also can check for id key if it is direct key of the object or object of object.
Skip the ID just at the indicated level using only "id"