Angular中如何将数组值按指定结构存储到目标对象中
Angular生成指定结构对象的问题修复方案
问题原因
- 直接push数组类型的
j.body.data.areas会导致newpublicarea成为二维数组,不符合结构要求 - 没有按照需求封装一层带
newpublicareas键的对象,而是直接把数组push进了entireareas - 额外说明:遍历数组无返回值需求时,用
map属于不必要的用法,建议替换为forEach
修复代码
场景1:j.body.data.areas为单个区域对象
getNewTopLevelS(res){ this.newpublicarea = [] res.forEach((j)=> { this.newpublicarea.push(j.body.data.areas) }) // 封装为目标结构 const result = { newpublicareas: this.newpublicarea } // 如需存入entireareas则执行下面的代码,不需要直接使用result即可 this.entireareas.push(result) }
场景2:j.body.data.areas为区域对象组成的数组
getNewTopLevelS(res){ this.newpublicarea = [] res.forEach((j)=> { // 展开数组推入单个元素,避免生成二维数组 this.newpublicarea.push(...j.body.data.areas) }) const result = { newpublicareas: this.newpublicarea } this.entireareas.push(result) }
补充说明
如果你的entireareas不需要是数组,直接存储目标对象的话,把this.entireareas.push(result)替换为this.entireareas = result即可。
内容的提问来源于stack exchange,提问作者Karthik J
相关产品推荐
相关产品推荐

