简体   繁体   English

使用javascript删除数组对象的属性

[英]Delete property of an array object using javascript

I have an array object in the below format and need to delete a property of an array.我有一个以下格式的数组对象,需要删除数组的一个属性。

Code:代码:

var partDetailArray={[PartId:100,PartRowID:'row-1']
,[PartId:100,PartRowID:'row-1']};
delete partDetailsArray.PartRowID;

I need to remove the PartRowID property from the array, but the delete statement isn't working.我需要从数组中删除PartRowID属性,但delete语句不起作用。

If you look in the console, you'll see that you're getting syntax errors with that code for the reasons I put in my comment on the question.如果您查看控制台,您会发现由于我在该问题的评论中提出的原因,该代码出现语法错误。

I'm going to guess you meant to have an array containing objects, like this:我猜你想拥有一个包含对象的数组,如下所示:

var partDetailArray = [
    {PartId:100,PartRowID:'row-1'},
    {PartId:100,PartRowID:'row-1'}
];

In that case, the array doesn't have a PartRowID property, but each of the objects in it does.在这种情况下,数组没有PartRowID属性,但其中的每个对象都有。 So we need to index into the array to access the object, and delete the property from it:所以我们需要对数组进行索引以访问对象,并从中删除属性:

delete partDetailsArray[0].PartRowID;
// Indexing into it ---^^^

That would delete that property from the first one.这将从第一个属性中删除该属性。 If you want to delete all of them, you'll need a loop:如果你想删除所有这些,你需要一个循环:

var index;
for (index = 0; index < partDetailArray.length; ++index) {
    delete partDetailsArray[index].PartRowID;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM