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

Time:11-17

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)

CodePudding user response:

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)
  • Related