I have the following object
const obj = {
"title": "sample",
"status": 0,
"creationDate": null,
"userGroup": "",
"signatureDelay": "2023-06-05T11:07:18.786Z",
"listSign": [],
"priority": false,
"nature": null,
"qesData": {
"signatories": [
{
"displayName": "Some user",
"email": "someuser@hotmail.com",
"firstname": "User first name",
"id": "4ffb81f6-6efd-4e41-9168-b032ab3e3b04",
"lastname": "User last name",
"locale": "en",
"signatoryAttributes": []
},
{
"email": "test@hotmail.com",
"displayName": "",
"areWeCreatingNewUser": true
},
{
"email": "test1@hotmail.com",
"displayName": "",
"areWeCreatingNewUser": true
}
]
},
"fileName": "sample.pdf",
}
I need to loop through the qesData => signatories array and remove all of the objects there which are having areWeCreatingNewUser property set to true.
So I tried
for(var i = 0;i < obj.qesData.signatories.length;i++) {
if(obj.qesData.signatories[i].areWeCreatingNewUser) {
obj.qesData.signatories.splice(i,1);
}
}
the problem here is that the first time when it founds the user with email test@hotmail.com it remove it with splice at index 1 and after that the obj.qesData.signatories is modified and on next iteration it does not remove the user with email test1@hotmail.com
How can I solve this issue ?
Also I forgot to mention that I need to use old javascript code,filter is not an option
>Solution :
You can use Array.filter() to do it
const obj = {
"title": "sample",
"status": 0,
"creationDate": null,
"userGroup": "",
"signatureDelay": "2023-06-05T11:07:18.786Z",
"listSign": [],
"priority": false,
"nature": null,
"qesData": {
"signatories": [
{
"displayName": "Some user",
"email": "someuser@hotmail.com",
"firstname": "User first name",
"id": "4ffb81f6-6efd-4e41-9168-b032ab3e3b04",
"lastname": "User last name",
"locale": "en",
"signatoryAttributes": []
},
{
"email": "test@hotmail.com",
"displayName": "",
"areWeCreatingNewUser": true
},
{
"email": "test1@hotmail.com",
"displayName": "",
"areWeCreatingNewUser": true
}
]
},
"fileName": "sample.pdf",
}
obj.qesData.signatories = obj.qesData.signatories.filter(d => !d.areWeCreatingNewUser)
console.log(obj)
Update: for ES5 style,below is a reference for you
const obj = {
"title": "sample",
"status": 0,
"creationDate": null,
"userGroup": "",
"signatureDelay": "2023-06-05T11:07:18.786Z",
"listSign": [],
"priority": false,
"nature": null,
"qesData": {
"signatories": [
{
"displayName": "Some user",
"email": "someuser@hotmail.com",
"firstname": "User first name",
"id": "4ffb81f6-6efd-4e41-9168-b032ab3e3b04",
"lastname": "User last name",
"locale": "en",
"signatoryAttributes": []
},
{
"email": "test@hotmail.com",
"displayName": "",
"areWeCreatingNewUser": true
},
{
"email": "test1@hotmail.com",
"displayName": "",
"areWeCreatingNewUser": true
}
]
},
"fileName": "sample.pdf",
}
let data = []
for(d of obj.qesData.signatories){
if(!d.areWeCreatingNewUser){
data.push(d)
}
}
obj.qesData.signatories = data
console.log(obj)