Reputation: 11040
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
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
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
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
Reputation: 5713
If you're trying to assign the value in the &&
operator, you need just one equals sign: PetForm[key] = ""
Upvotes: 1