Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to ignore null or blank value while writing to JSON using NodeJS

I’m writing below content to JSON file, I would like to ignore the fields which has value null or blank – in this case I want to ignore productPrice and productRating fields while writing to JSON file, I’m not much familiar with NodeJS – can someone please help how can I achieve this in NodeJS?

Please find my code below:

const fs = require('fs');

const params = {
    productID: 'prd323434',
    productName: 'Google',
    productDesc: 'Larum ipsum',
    productPrice: null,
    productRating: '',
    productReview: 'Lorum ipsum'
};

var data = {
    productID: params.productID,
    productName: params.productName,
    productDesc: params.productDesc,
    productPrice: params.productPrice,
    productRating: params.productRating,
    productReview: params.productReview
};

let jsonContent = JSON.stringify(data);
fs.writeFileSync('test.json', jsonContent);

console.log(jsonContent)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You look like you are just filtering your object for "falsy" values.

So take params, use Object.entries on it to get something like this:

[
 [productID, 'prd323434'],
 [productName, 'Google'],
 ...
]

Use the filter method on the result, destructure each param with ([k,v]). Then only return it if v is "truthy".

const data = Object.fromEntries(Object.entries(params).filter(([k,v]) => v))

Or perhaps in a more readable way:

const entries = Object.entries(params)
const filtered = entries.filter(([k,v]) => {
  if (v === null || v === "") {
    return false
  } else {
    return true
  }
}))
const data = Object.fromEntries(filtered)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading