Home > other >  Sending client a NodeJS object with some undefined property values
Sending client a NodeJS object with some undefined property values

Time:04-22

I'm running a PostgreSQL query:

'SELECT * FROM table'

On my server side, I'm trying to generate a JSON object of the below format, but some of the column# values are set to 'undefined' because the row.value# is undefined:

{
  column1: row.value1,
  column2: row.value2,
  column3: row.value3,
  column4: row.value4,
  column5: row.value5,
  column6: row.value6,
  column7: row.value7,
  column8: row.value8,
  column9: row.value9,
}

On my client side, I'm trying to receive a set of JSON objects, but they don't have the same format because whenever one of the column#'s has a value of undefined, it's removed from the JSON object so that it looks like the below (because column5, column6, and column8 were undefined).

{
  column1: row.value1,
  column2: row.value2,
  column3: row.value3,
  column4: row.value4,
  column7: row.value7,
  column9: row.value9,
}

My solution was to give the properties in the JSON object a default value in case of the row.value# being undefined. How can I do this (replace 'undefined' with some default value in the object).

CodePudding user response:

You can use a ternary operator (? :) like this:

const row = {
  value2: "Praveen",
  value6: "Kumar",
  value8: "Purushothaman"
};

console.log({
  column1: row.value1 ? row.value1 : "NA",
  column2: row.value2 ? row.value2 : "NA",
  column3: row.value3 ? row.value3 : "NA",
  column4: row.value4 ? row.value4 : "NA",
  column5: row.value5 ? row.value5 : "NA",
  column6: row.value6 ? row.value6 : "NA",
  column7: row.value7 ? row.value7 : "NA",
  column8: row.value8 ? row.value8 : "NA",
  column9: row.value9 ? row.value9 : "NA",
});

This gives me an output of:

{
  "column1": "NA",
  "column2": "Praveen",
  "column3": "NA",
  "column4": "NA",
  "column5": "NA",
  "column6": "Kumar",
  "column7": "NA",
  "column8": "Purushothaman",
  "column9": "NA"
}

There is a way to use null coalescing operator too. But that might not be supported always. However, the above logic works every time.

CodePudding user response:

You can do something like this

const defaultValues = {
  col1: "col1",
  col2: "col2",
  col3: "col3"
};

const fromApi = {
col2 : 'my value col2'
}


const result = {...defaultValues, ...fromApi}

console.log(result)

  • Related