We can use a function instead of an array as the
replacer
let room = {
number: 23
};
let meetup = {
title: "Conference",
participants: [{name: "John"}, {name: "Alice"}],
place: room // meetup references room
};
room.occupiedBy = meetup; // room references meetup
// All the properties (except occupiedBy) are the encoded
document.write( JSON.stringify(meetup, function replacer(key, value) {
return (key == 'occupiedBy') ? undefined : value;
}));
The function will be called for every
(key, value)
pair and should return the
replaced
value, which will be used instead of the original one. Or
undefined
if the value is to be skipped.
...
In our case, we can return
value
“as is” for everything except
occupiedBy
. To ignore
occupiedBy
, the code above returns
undefined
.
The result of the code above will be the following:
{"title":"Conference","participants":[{"name":"John"},{"name":"Alice"}],"place":{"number":23}}
As we expected all the values are encoded except
occupiedBy