[英]How to remove an empty object from an array?
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. 我有一个JavaScript对象数组,单击按钮时,我将一个对象推入数组,然后将其用作网格的数据源。 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. 您可以利用
else
来警告消息,指出用户将某些输入留空。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.