Home > Enterprise >  Change all blank ("") keys in object to null [closed]
Change all blank ("") keys in object to null [closed]

Time:09-30

Say I have an object with nested keys:

const person = {
  firstName: "John",
  lastName : "Doe",
  id       : 5566,
  nicknames: ["Johnny", "Jonathan"],
  birthDate: "", // blank string. 
};

How do i programmatically change object keys so all values that are blank ("") change to null? Like this:


const person = {
  firstName: "John",
  lastName : "Doe",
  id       : 5566,
  nicknames: ["Johnny", "Jonathan"],
  birthDate: null, // null instead of blank string. 
};

I would prefer a solution without external modules/NPM packages. Thanks in advance…

CodePudding user response:

You can iterate through each property and check whether the value is a blank string, and if so, set it to null:

const person = {
  firstName: "John",
  lastName : "Doe",
  id       : 5566,
  nicknames: ["Johnny", "Jonathan"],
  birthDate: "", // blank string. 
};

Object.keys(person).forEach(e => person[e] = person[e] == "" ? null : person[e])

console.log(person)

  • Related