1

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?

0

4 Answers 4

3

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)

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

Can you please elaborate your answer through a quick code snippet. It really helps!
1

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)

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.