Set The Default Value For The Object In Javascript
Solution 1:
You could create a default object with the default properties and use Object.assign()
like this:
function addAlert(stringValue, valueObject) {
const defaultObj = {
status: "default status",
position: "default position",
align: "default align"
};
valueObject = Object.assign({}, defaultObj, valueObject)
console.log(valueObject)
}
addAlert('', { status: "status" })
addAlert('', { position: "position", align: "align" })
addAlert('') // valueObject will be undefined
.as-console-wrapper { max-height: 100% !important; top: 0; }
Solution 2:
you can set the parameters default values as follows:
addAlert(stringValue = 'default string',valueObject = {}) {
//Set the default values for the valueObject
}
For more info please visit Default_parameters
Solution 3:
You can use Object.assign
to create an object with default values:
const defaults = {
a: 1,
b: 2,
c: 3
}
const obj1 = { a: 11 }
const obj2 = { a: 11, c: 33}
const obj3 = { a: 11, b: 22, c: 33 }
const newObj1 = Object.assign({}, defaults, obj1);
const newObj2 = Object.assign({}, defaults, obj2);
const newObj3 = Object.assign({}, defaults, obj3);
console.log(newObj1);
console.log(newObj2);
console.log(newObj3);
Alternatively, you can do the same using spread syntax:
const defaults = {
a: 1,
b: 2,
c: 3
}
const obj1 = { a: 11 }
const obj2 = { a: 11, c: 33}
const obj3 = { a: 11, b: 22, c: 33 }
const newObj1 = { ...defaults, ...obj1};
const newObj2 = { ...defaults, ...obj2};
const newObj3 = { ...defaults, ...obj3};
console.log(newObj1);
console.log(newObj2);
console.log(newObj3);
You can use either of these to set the default values:
addAlert(stringValue,valueObject) {
const defaults = { status: "INFO", position: "TOP": align: "LEFT" };
const settings = Object.assign({}, defaults, valueObj);
/* use settings in the code */
}
or
addAlert(stringValue,valueObject) {
const defaults = { status: "INFO", position: "TOP": align: "LEFT" };
const settings = { ...defaults, ...valueObj };
/* use settings in the code */
}
Solution 4:
The best way to do that is just to give in the call of the function the default value with it:
addAlert(stringValue = 'default',valueObject = 'default') {
//Set the default values for the valueObject
}
Now if you want to give a default Value for stringObject.status you have two options: You check if they are undefined and than set give them a default value:
addAlert(stringValue,valueObject) {
if (valueObject.status == undefined) {
valueObject.status = 'default';
}
}
Or you will pass the three diffrent fields all single.
addAlert(stringValue,valueObject.status, etc..) {
//Set the default values for the valueObject
}
Hope this helps! :)
Solution 5:
You can assign the default values in the parameter list it self in the below manner.
addAlert = (stringValue="defaultString",valueObject={status:"", position:"", align:""})=> {
console.log(stringValue, valueObject)
}
Post a Comment for "Set The Default Value For The Object In Javascript"