如何将嵌套JavaScript对象的totalInputRate插入目标对象?技术求助
解决嵌套JavaScript对象中插入
totalInputRate字段的问题 你遇到的核心问题是在构建目标对象时,没有把原始数据里的totalInputRate字段纳入最终结构中。下面是一个直接有效的解决方案,帮你补全缺失的字段:
解决方案代码
const data = { periods: [ { decisions: [ { bank: { name: "Team1" }, bSPositionDecisions: [ { totalInputRate: 1.0, balanceSheetPosition: { name: "asset_bc_lombard_a_onsight", category: "LOMBARD_LOANS", type: "ASSET" } }, { totalInputRate: 2.0, balanceSheetPosition: { name: "asset_bc_lombard_a_lt1m", category: "LOMBARD_LOANS", type: "ASSET" } } ] }, { bank: { name: "Team2" }, bSPositionDecisions: [ { totalInputRate: 5.0, balanceSheetPosition: { name: "asset_bc_lombard_a_onsight", category: "LOMBARD_LOANS", type: "ASSET" } }, { totalInputRate: 6.0, balanceSheetPosition: { name: "asset_bc_lombard_a_lt1m", category: "LOMBARD_LOANS", type: "ASSET" } } ] } ] } ] }; // 初始化目标输出对象 const bankname = { banks: [] }; // 逐层遍历原始嵌套数据 data.periods.forEach(period => { period.decisions.forEach(decision => { const currentBankName = decision.bank.name; // 查找目标对象中是否已有该银行的条目,没有则新建 let bankEntry = bankname.banks.find(bank => bank.name === currentBankName); if (!bankEntry) { bankEntry = { name: currentBankName }; bankname.banks.push(bankEntry); } // 处理每个银行的头寸决策 decision.bSPositionDecisions.forEach(posDecision => { const { totalInputRate } = posDecision; const { name, category } = posDecision.balanceSheetPosition; // 初始化分类数组(如果当前银行还没有该分类) if (!bankEntry[category]) { bankEntry[category] = []; } // 将包含totalInputRate的完整对象推入分类数组 bankEntry[category].push({ totalInputRate, name, category }); }); }); }); console.log(bankname);
关键逻辑说明
- 目标结构初始化:先创建一个包含空
banks数组的对象,作为最终输出的基础框架。 - 逐层遍历匹配:从最外层的
periods开始,深入到每个银行的bSPositionDecisions,确保不会遗漏任何一条数据。 - 银行条目管理:对每个银行,先检查目标对象中是否已有对应条目,避免重复创建。
- 补全缺失字段:在组装头寸条目时,明确把
totalInputRate和balanceSheetPosition里的字段一起放入新对象——这就是你之前输出里缺失的核心步骤。
运行这段代码后,就能得到你期望的输出结构,每个头寸条目都会包含对应的totalInputRate值。
内容的提问来源于stack exchange,提问作者Clive Charles
相关产品推荐
相关产品推荐

