【发布时间】:2021-08-21 04:10:26
【问题描述】:
我有类似的 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"
}
]
}
]
}
]
我需要从这些 json 中修复 2 个问题:
- 检查
value是否与JSON中的id匹配 - 如果通过值找到
JSON的id并且id索引是最新索引,则删除元素
我可以用当前代码处理1st task:
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'))
但我坚持第二个任务,预期结果如下:
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'
有人建议解决我的第二个问题吗?
【问题讨论】:
-
您需要更具体地说明什么是“最新”。是从索引 5 开始的任何数字,还是更复杂的数字?
-
嵌套级别有多深?是问题中显示的还是可以更深入?
-
@Tibrogargan,由于不保证 id 是递增的,我可以说它只是任何数量的 id
-
@decpk 目前嵌套深度的数组就像 JSON 创建的一样
-
这没有帮助。您需要提供一些定义明确的机制来确定什么是最新的?显然,“id”实际上是两条(或更多条)信息组合在一起产生一个标识符,但公式是什么?它总是一个 5 个字母的前缀后跟一个数字,还是可以是“后面的任何内容 - 后跟一些数字,后跟一个或多个字母,后跟一个数字”。即
ABCDEFG13854761324-7864784JHKFLKHFJG0可能是合法的
标签: javascript json recursion