I have JSON something like:
[
{
"property": "Foo",
"address": "Foo Address",
"debitNote": [
{
"title": "Debit A Foo",
"desc": "Desc Debit Foo",
"listDebit": [
{
"id": "IP-1A1",
"amount": "273000"
},
{
"id": "IP-1A2",
"amount": "389000"
},
{
"id": "IP-1A3",
"amount": "382000"
},
{
"id": "IP-1A4",
"amount": "893000"
},
{
"id": "IP-1A5",
"amount": "1923000"
}
]
},
{
"title": "Debit B Foo",
"desc": "Desc Debit B Foo",
"listDebit": [
{
"id": "IP-1B1",
"amount": "120000"
},
{
"id": "IP-1B2",
"amount": "192000"
}
]
}
]
},
{
"property": "Bar",
"address": "Address Bar",
"debitNote": [
{
"title": "Debit A Bar",
"desc": "Desc Bar",
"listDebit": [
{
"id": "IP-1C1",
"amount": "893000"
},
{
"id": "IP-1C2",
"amount": "1923000"
}
]
},
{
"title": "Debit B Bar",
"desc": "Desc Debit B Bar",
"listDebit": [
{
"id": "IP-1D1",
"amount": "192000"
}
]
}
]
}
]
I need to fix 2 problem from those json:
- check if
valueis match with id insideJSON - remove element if
idofJSONis found by value and theidindex is the latest index
I can handle the 1st task with current code:
let json = [{"property":"Foo","address":"Foo Address","debitNote":[{"title":"Debit A Foo","desc":"Desc Debit Foo","listDebit":[{"id":"IP-1A1","amount":"273000"},{"id":"IP-1A2","amount":"389000"},{"id":"IP-1A3","amount":"382000"},{"id":"IP-1A4","amount":"893000"},{"id":"IP-1A5","amount":"1923000"}]},{"title":"Debit B Foo","desc":"Desc Debit B Foo","listDebit":[{"id":"IP-1B1","amount":"120000"},{"id":"IP-1B2","amount":"192000"}]}]},{"property":"Bar","address":"Address Bar","debitNote":[{"title":"Debit A Bar","desc":"Desc Bar","listDebit":[{"id":"IP-1C1","amount":"893000"},{"id":"IP-1C2","amount":"1923000"}]},{"title":"Debit B Bar","desc":"Desc Debit B Bar","listDebit":[{"id":"IP-1D1","amount":"192000"}]}]}]
function findID(array, value){
return array.some((item)=>{
if(item.id == value) {
return true
}
return Object.keys(item).some(x=>{
if(Array.isArray(item[x])) return findID(item[x], value)
})
})
}
console.log(findID(json, 'IP-1D1'))
console.log(findID(json, 'IP-1A1'))
console.log(findID(json, 'IP-1B1'))
console.log(findID(json, 'IP-1Z1'))
But I'm stuck with the 2nd task with the expected result as follow:
console.log(removeID(json, 'IP-1A5')) // {"id": "IP-1A5", "amount": "1923000"} removed
console.log(removeID(json, 'IP-1A3')) // couldn't remove, because there's {"id": "IP-1A4", "amount": "893000"} after id 'IP-1A3'
anyone suggestion to fix my 2nd problem?
ABCDEFG13854761324-7864784JHKFLKHFJG0could be legitimate