我有一个JS对象data
,从该对象数组中,我需要获取位于“ limitBreakup”数组内的“ amount”值。我已经使用.map()
完成了,但是我很想知道使用Recursion
var data = [
{
"limitRequirementId":"123",
"facilityType":"cc",
"amount":800000,
"existingRoi":12,
"existingPf":12100,
"repoRate":5,
"spread":10,
"tenure":24,
"margin":10000,
"loanVariable":{
"type":"roi/commission",
"value":15
},
"limitBreakup":[
{
"limitRequirementId":"13",
"facilityType":"cc",
"repoRate":5,
"amount":8000,
"spread":10,
"tenure":24,
"margin":100,
"loanVariable":{
"type":"roi/commission",
"value":15
}
},
{
"limitRequirementId":"22",
"facilityType":"LC",
"repoRate":4,
"amount":900,
"spread":6,
"tenure":21,
"margin":15,
"loanVariable":{
"type":"roi/commission",
"value":10
}
}
]
},
{
"limitRequirementUniqueId":"13",
"limitRequirementId":"13",
"facilityType":"lc",
"amount":900000,
"existingRoi":10,
"existingPf":1000,
"repoRate":3,
"spread":1,
"tenure":21,
"margin":1000,
"loanVariable":{
"type":"roi/commission",
"value":15
},
"limitBreakup":[
{
"limitRequirementId":"35",
"facilityType":"CC",
"repoRate":6,
"amount":600,
"spread":8,
"tenure":28,
"margin":13,
"loanVariable":{
"type":"roi/commission",
"value":14
}
}
]
}
]
使用常规迭代的我的解决方案有效:
data.forEach((d, i)=>{
let limitBreakup = d.limitBreakup;
if(Array.isArray(limitBreakup)){
limitBreakup.forEach((l)=>{ console.log(l, '->', l.amount) })
}else{
console.log(limitBreakup, 'else->', limitBreakup.amount)
}
//console.log(d.limitBreakup);
})
但是使用递归,我已经中途了:
https://jsfiddle.net/1g98sLw3/2/
http://www.mocky.io/v2/5ea974eb3400005e003f0203(由于json对象很大,因此我已粘贴到放了mathy.io中以供参考)
这样的事情应该起作用
演示证明:https://jsfiddle.net/t1z36d0u/
您需要循环来遍历对象,然后在满足条件时将它们添加到数组中
let amountArr = [];
function getMyAmount(data) {
for (let i = 0; i < data.length; i++) {
const obj= data[i];
if (obj.hasOwnProperty('limitBreakup')) {
if (obj.hasOwnProperty('amount')) {
amountArr.push(obj.amount)
} else {
console.log(obj)
getMyAmount(obj.limitBreakup)
}
}
}
};
getMyAmount(data)