I have this object:
{
name: "",
email: "",
phone: "",
protocol: "",
area: "",
subject: "",
message: "",
validation: this.validator.valid()
}
I wanna convert it to JSON, but I do not want the validation
property on it.
I've already tried the following:
const test = JSON.stringify(this.state);
delete test.validation;
Any other approach?
I have this object:
{
name: "",
email: "",
phone: "",
protocol: "",
area: "",
subject: "",
message: "",
validation: this.validator.valid()
}
I wanna convert it to JSON, but I do not want the validation
property on it.
I've already tried the following:
const test = JSON.stringify(this.state);
delete test.validation;
Any other approach?
Share Improve this question edited Jul 21, 2019 at 19:22 Philipp 4751 gold badge4 silver badges19 bronze badges asked May 10, 2019 at 16:39 Guilherme L. MoraesGuilherme L. Moraes 1223 silver badges14 bronze badges 7- you want to select which property to stringify? – Diagathe Josué Commented May 10, 2019 at 16:42
- Yeah, @Webwoman I've updated the question: look what've tried. It worked for me ;) – Guilherme L. Moraes Commented May 10, 2019 at 17:25
- Ok, @Yunnosch, im sorry. I'll do it – Guilherme L. Moraes Commented May 10, 2019 at 17:37
- No problem, well done now. – Yunnosch Commented May 10, 2019 at 18:42
- Possible duplicate of Excluding object properties while json-stringifying array object – Heretic Monkey Commented Jul 21, 2019 at 19:08
4 Answers
Reset to default 9JSON.stringify
takes a replacer callback you can use. The replacer function takes a key k
and the value v
being stringified as parameters. Returning undefined will have the effect of not including the key in the final result:
state = {
name: "",
email: "",
phone: "",
protocol: "",
area: "",
subject: "",
message: "",
validation: "some val"
}
const test = JSON.stringify(state, (k, v) => k != 'validation' ? v : undefined);
console.log(test)
Note: used like this it will remove the validation
key from any child objects as well, which may or may not be what you want.
It will work.
const { validation, ...rest } = this.state;
JSON.stringify(rest);
UPDATE - I found a different solution
It's very simple, in fact. I've discovered the solution here. The following lines solved my problem:
const formSubmit = JSON.stringify(this.state, ['name', 'email', 'phone', 'protocol','area','subject', 'message']);
If you put an undefined, JSON.stringify will skip it:
const yourState = {
name: "",
email: "",
phone: "",
protocol: "",
area: "",
subject: "",
message: "",
validation: true,
}
const copy = {
...yourState,
validation: undefined,
};
console.log(JSON.stringify(copy));
Also, you can not perform a delete from JSON.stringify because it is a string an not an object literal.