1

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?

Philipp
  • 475
  • 4
  • 18

4 Answers4

9

JSON.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.

Mark
  • 90,562
  • 7
  • 108
  • 148
  • Thanks, man! I found the answer b'cause of your post. I've updated the question with my solution: what do you think of it? There's any problem? I'm brand new to this whole thing ;) – Guilherme L. Moraes May 10 '19 at 17:27
  • can you extrapolate the meaning of `k` and `v` for the future readers please – Webwoman May 10 '19 at 17:44
  • 1
    Sure @Webwoman, I added some extra text explaining it. Hope it helps. – Mark May 10 '19 at 17:49
2

It will work.

const { validation, ...rest } = this.state;
JSON.stringify(rest);
Ehsan
  • 1,093
  • 1
  • 12
  • 21
2

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']);
1

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.

Jose Mato
  • 2,709
  • 1
  • 17
  • 18