I have a JavaScript Array of Objects, on a button click I push an object into the array and then use that as a datasource for a grid. The issue I am facing is that initially the first object in the array is all blank values and when I load the grid I have a blank row because of the empty object... How do I remove that empty object from the array before I load the grid?
Here is the array
var gridData = {
step3GridData: [{ Description: "", Color: "", SqSiding: "" }]
};
and on a button click I am pushing a new object to the array
gridData.step3GridData.push({ Description: $("#InfoInsul").text(), Color: $("#ddGetInsulationMaterialColor").val(), SqSiding: $("#ddInsulationSquares").val() });
LoadStep3(gridData.step3GridData);
As mentioned, I need to remove that empty object before I bind the load with the array. How would I go about doing this?
Use splice . If you are certain it is always the first item in the array, you can do:
if (gridData.length && Object.keys(gridData[0]).length === 0) {
gridData.splice(0, 1);
}
If you are not certain about its position, you can traverse the array and remove the first empty object:
for (const [idx, obj] of gridData.entries()) {
if (Object.keys(obj).length) === 0) {
gridData.splice(idx, 1);
break;
}
}
First, initialize your array like this:
var gridData = {
step3GridData: [] // empty array
};
Then when you are pushing a new object, check if the inputs are filled like this:
var desc = $("#InfoInsul").text(); // this seems unnecessary as this is not left to the user to fill (if I'm assuming right then don't check if this is empty)
var col = $("#ddGetInsulationMaterialColor").val();
var sqs = $("#ddInsulationSquares").val();
if(desc.length && col.length && sqs.length) { // if desc is not empty and col is not empty and sqs not empty then add an object
gridData.step3GridData.push({ Description: desc, Color: col, SqSiding: });
}
Now if the user left something empty, the object won't get pushed, thus there will be no empty objects. You can make use of else
to alert a message saying that the user left some input blank.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.