Home > Back-end >  undefined properties not being added to object
undefined properties not being added to object

Time:11-19

I have the following code:

let object = {};
Object.keys(this.graphQL.body).forEach((key) => {
    console.log(key, this[key])
    object[key] = this[key]
})
let json = JSON.stringify(object);
console.log('API json', json)

Which gives this out this console log:

id undefined
title undefined
filename mitchel-lensink-Y2OCQVuz6XM-unsplash.jpg
description undefined
keywords undefined
assetID undefined
height undefined
width undefined
uploadOwnerType image
uploadOwnerID 100513
createdAt undefined
updatedAt undefined
API json {"filename":"mitchel-lensink-Y2OCQVuz6XM-unsplash.jpg","uploadOwnerType":"image","uploadOwnerID":100513}

Why do I not get the undefined keys added? And how can I add them anyway?

CodePudding user response:

JSON.stringify method removes undefined keys by default.

let json = JSON.stringify(object);

To keep these, we can use a replacer -

let object = {};
Object.keys(this.graphQL.body).forEach((key) => {
    console.log(key, this[key])
    object[key] = this[key]
})

const replacer = (key, value) =>
  typeof value === 'undefined' ? null : value;

let json = JSON.stringify(object, replacer);
console.log('API json', json)

Let me know in the comments if need any further elaboration.

CodePudding user response:

Undefined keys are added but JSON.stringify omits all fields with undefined values. To add undefined valued keys you can use replacer function:

const replacer = (key, value) =>
  typeof value === 'undefined' ? null : value;

And then send this as second parameter to JSON.stringify function

let json = JSON.stringify(object, replacer);

Check this blog post for more information: https://muffinman.io/blog/json-stringify-removes-undefined/

  • Related