After deleting an object property using delete objec.prop3[1] , null is getting replaced in that object property's place.
for ex:
objec: {
prop1: "aa",
prop2: "bb",
prop3: [{
item1: "i1",
item2: "i2"
}, {
item1: "i3",
item2: "i4"
}]
}
for deleting {
item1: "i3",
item2: "i4"
}
i am using
for (i = 0; i < objec.prop3.length; i++) {
if (objec.prop3[i].item2 == "i4") {
delete object.prop3[i]
}
}
obtained output:
objec: {
prop1: "aa",
prop2: "bb",
prop3: [{
item1: "i1",
item2: "i2"
},
null
]
}
required output:
objec: {
prop1: "aa",
prop2: "bb",
prop3: [{
item1: "i1",
item2: "i2"
}]
}
You are trying to delete an element from a array and not a key value pair, to do that you can not use delete
instead use some method to delete an element from array..
for (i = 0; i < objec.prop3.length; i++) {
if (objec.prop3[i].item2 == "i4") {
object.prop3.splice(i, 1);
}
}
The splice()
method adds/removes items to/from an array, and returns the removed item(s).
Note: This method changes the original array.
array.splice(index,howmany,item1,.....,itemX)
index: Required. An integer that specifies at what position to add/remove items, Use negative values to specify the position from the end of the array
howmany: Required. The number of items to be removed. If set to 0, no items will be removed
item1, ..., itemX: Optional. The new item(s) to be added to the array
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.