You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 06:24:00