0

I am trying create json request body. where most of the fields are optional. I want to keep them if the value is defined for them or remove if they are undefined.

 
let payalod = data {
id: 1,
type: "sale"
name: undefined // optional 
}

I want to keep the name property optional. means if the value is undefied we can remove if before sending the request. if guess it can be achived with a ? sing (optional chaining). but not able to get the syntax.

can anyone help me with optional chaining approach TIA.

Sameer Salim
  • 1
  • 1
  • 3

2 Answers2

1

You can iterate through the object and delete the undefined properties:

let payload = {
  "id": 1,
  "type": "sale",
  "name": undefined // optional 
};

for (var key of Object.keys(payload)) {
    if (!payload[key]) {
      delete payload[key];
    }
};

console.log(payload);
Sam
  • 705
  • 1
  • 9
  • 18
1

You can do (Hide null values in output from JSON.stringify()):

data = {id: 1, type: "sale", name: undefined}

var payload = JSON.parse(JSON.stringify(data, (key, value) => {
    if (value !== null) return value
}))
YamirL
  • 65
  • 2
  • 8