Reputation: 2541
Following is my code, in which I am trying to add passStatus
to an object only if it has a value otherwise omit it.
I tried this one - In Javascript, how to conditionally add a member to an object?
But seems like I am doing it wrong. Any pointers Please.
Code -
var a = {
firstName: "Tom",
lastName: "Simmon",
email: "[email protected]",
phone: "+36456",
passStatus: "",
query: "simple"
};
// var newObj = Object.assign(a, a.passStatus ? {a.passStatus} : null);
var newObj = {
...(a.passStatus? {passStatus: a.passStatus}: {} )
}
console.log(newObj); // {} <- Getting a blank object
Expected Output -
If passStatus = ""
{
firstName: "Tom",
lastName: "Simmon",
email: "[email protected]",
phone: "+36456",
query: "simple"
}
If passStatus = "pass"
{
firstName: "Tom",
lastName: "Simmon",
email: "[email protected]",
phone: "+36456",
passStatus: "pass",
query: "simple"
}
Upvotes: 0
Views: 323
Reputation: 191976
Destructure the object (a
) to remove the value, than use object spread to add it, if it's truthy:
var a = {
firstName: "Tom",
lastName: "Simmon",
email: "[email protected]",
phone: "+36456",
query: "simple"
};
const { passStatus, ...obj } = a;
const newObj = {
...obj,
...(passStatus && { passStatus })
};
console.log(newObj);
Upvotes: 4
Reputation: 202686
Shallow copy the entire object, if the new object has a falsey passStatus
value, delete the property.
const a = {
firstName: "Tom",
lastName: "Simmon",
email: "[email protected]",
phone: "+36456",
passStatus: "",
query: "simple"
};
const b = {
firstName: "Tom",
lastName: "Simmon",
email: "[email protected]",
phone: "+36456",
passStatus: "test",
query: "simple"
};
const copyKeepOrRemovePassStatus = obj => {
const newObj = { ...obj };
if (!newObj.passStatus) {
delete newObj.passStatus;
}
return newObj;
};
console.log(copyKeepOrRemovePassStatus(a));
console.log(copyKeepOrRemovePassStatus(b));
Upvotes: 1
Reputation: 370699
I think the clearest way to conditionally remove a property from the object like this would be to use rest syntax followed by a possible Object.assign
:
var a = {
firstName: "Tom",
lastName: "Simmon",
email: "[email protected]",
phone: "+36456",
passStatus: "",
query: "simple"
};
const { passStatus, ...newObj } = a;
if (passStatus) {
Object.assign(newObj, { passStatus });
}
console.log(newObj);
You can do it in one line by destructuring a computed property name, where the property name uses the conditional operator to remove the passStatus
property if it exists - but this is hard to understand, I wouldn't recommend it:
var a = {
firstName: "Tom",
lastName: "Simmon",
email: "[email protected]",
phone: "+36456",
passStatus: "",
query: "simple"
};
const { [a.passStatus ? '' : 'passStatus']: _, ...newObj } = a;
console.log(newObj);
Upvotes: 1