Guilherme L. Moraes
Guilherme L. Moraes

Reputation: 122

JSON Stringfy only a few properties

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?

Upvotes: 1

Views: 2520

Answers (4)

Mark
Mark

Reputation: 92440

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.

Upvotes: 9

Guilherme L. Moraes
Guilherme L. Moraes

Reputation: 122

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

Upvotes: 2

Jose Mato
Jose Mato

Reputation: 2799

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.

Upvotes: 1

Ehsan
Ehsan

Reputation: 1113

It will work.

const { validation, ...rest } = this.state;
JSON.stringify(rest);

Upvotes: 2

Related Questions