【问题标题】:how to add new object to the existing dynamic response using angular如何使用角度向现有动态响应添加新对象
【发布时间】:2018-09-07 06:25:37
【问题描述】:

我从服务器得到这个动态响应。在这里我想将我的 mapD 数据推送到 mapData(即动态数据)中;

[
      {
        Name: "Aura",
        OrderState: "2",
        latitude: "28.197619999999997",
        longitude: "65.24778333333334"
      }
    ]

我将上述动态响应存储为 this.mapData = res.Data 。

我也有静态数据,例如

public mapD:any=[{
    Name: "mad",
    OrderState: "2",
    latitude: "39.6868",
    longitude: "83.2185"
    }]

我希望上面的这个静态对象包含动态对象,这样我总共会得到 2 个对象 - 我正在使用 push 方法但无法使用获取数据

this.mapD.push(this.mapData)

我使用mapData 保存响应并在模板中循环

【问题讨论】:

  • I will get 2 objects in total - 你的意思是 mapD 数组中的两个对象?
  • 令 newArr = [...firstArray, ...secondArray];
  • @mplungjan no in mapData
  • 您收到了一个数组。如果数组总是只有一个 uniqe 元素,你必须这样做 this.mapD.pus(this.mapData[0])

标签: javascript angular typescript javascript-objects


【解决方案1】:

您不能将一个数组推入另一个数组。请改用spread

this.mapD.push(...this.mapData);

如果你不能使用 ES6,或者 array.concat:

this.mapD = this.mapD.concat(this.mapData);

【讨论】:

  • 通过使用扩展运算符我得到以下错误——无法读取未定义的属性“应用”——我使用 mapData 保存响应并将其循环到模板this.mapData
  • 像这样初始化你的地图数据.mapData=[];
  • 你可以像这样使用安全调用this.mapD.push(...(this.mapData || []));
【解决方案2】:

我不确定你的意思,但如果你想将返回的数组 mapData 合并到现有的 mapD 中,你可以尝试以下操作:

Array.prototype.push.apply(this.mapD, this.mapData);

它将结果存储在this.mapD

希望对你有帮助,

【讨论】:

    【解决方案3】:

    您可以将mapD 声明为mapData 的数组,以便稍后访问您的对象属性。一个简单的例子:

    mapData: Array<any>
    mapD: Array<any>
    
    getResponse() {
       this.yourApiService.subscribe(
          (response: Array<any>) => {
              this.mapDdata = response;
              // Loop through the response array here or push first item
              this.mapD.push(reponse[0]);
          }
       );
    }
    

    现在你有了mapD,它是数组类型,包含你映射的mapData 对象。这允许您访问存储在该数组中的对象的属性。

    【讨论】:

    • 我将我的响应存储在 mapData 中
    • 我已更新以上内容,将您的回复添加到 mapData 下。如果您希望将响应附加到静态数组中,则应在响应之后立即推送它。
    猜你喜欢
    • 1970-01-01
    • 2016-02-08
    • 2019-06-26
    • 1970-01-01
    • 2020-05-02
    • 2011-02-25
    • 2017-05-26
    • 2012-06-18
    • 2018-04-26
    相关资源
    最近更新 更多