lost9123193
lost9123193

Reputation: 11040

Replace Object Fields

I have an object that looks like this:

PetForm

{
name:"Bobo",
type:"Golden Retriever",
food:null,
toys:null,
....
}

I want to replace the fields with the values of null to an empty string like this:

Result:

{
name:"Bobo",
type:"Golden Retriever",
food:"",
toys:"",
....
} 

I did the following:

Object.keys(PetForm).forEach((key) => (PetForm[key] === null) && PetForm[key] == "");

Am I missing something in this method?

Upvotes: 1

Views: 88

Answers (4)

Shammel Lee
Shammel Lee

Reputation: 4475

var obj = {
name:"Bobo",
type:"Golden Retriever",
food:null,
toys:null
};

for (var key in obj) {
  if (obj.hasOwnProperty(key)) {
    (obj[key] === null) && (obj[key] = '');
  }
}

console.log(obj);

Upvotes: 0

Mμ.
Mμ.

Reputation: 8542

In case you want to keep the petform map and return a new object, you can use reduce function.

var petform = {
  name:"Bobo",
  type:"Golden Retriever",
  food:null,
  toys:null,
}

var res = Object.keys(petform).reduce((acc, curr) => { acc[curr] = petform[curr] ? petform[curr] : '' ; return acc; }, {});

console.log(res)

Upvotes: 1

brk
brk

Reputation: 50326

var petForm = {
  name: "Bobo",
  type: "Golden Retriever",
  food: null,
  toys: null
}
Object.keys(petForm).forEach(function(item) {
  if (petForm[item] === null) {

    petForm[item] = "";
  }

})

console.log(petForm)

Upvotes: 3

hughes
hughes

Reputation: 5713

If you're trying to assign the value in the && operator, you need just one equals sign: PetForm[key] = ""

Upvotes: 1

Related Questions