简体   繁体   English

在RxJS中合并两个对象

[英]Combine two object in RxJS

I am working with rxjs and angular 2 inside of a service. 我正在服务中使用rxjs和angular 2。 I have some json that I was able to access with a get request. 我有一些可以通过get请求访问的json。

   private _campInfoUrl = 'api/campInfo/campInfo.json';
  constructor(private _http: Http) { }

  getAvailableCamps() {  
    return this._http.get(this._campInfoUrl)
      .map((response: Response) => response.json())

At this point I have all of the data. 至此,我已经掌握了所有数据。 However to get into this object 但是要进入这个对象

      {
       "search": {
       "startDate": "2016-06-07",
       "endDate": "2016-06-10"
      },
       "reservations": [
       {"campsiteId": 1, "startDate": "2016-06-01", "endDate": "2016-06-04"},
       {"campsiteId": 1, "startDate": "2016-06-11", "endDate": "2016-06-13"},
       {"campsiteId": 2, "startDate": "2016-06-08", "endDate": "2016-06-09"}
  ] 
}

this is what i am trying to do 这就是我想要做的

.map((response: Response) => response.json()) // <IProduct[]>
  .map((tripDate) => ({
    reservations: tripDate.reservations,
    newRes: tripDate.search // <-- how to add this to every return object
  }))

What I am struggling to figure out is a way with rxjs on how to get "search" inside of reservations array of objects like so 我正在努力寻找的是使用rxjs的一种方法,该方法如何在对象的预留数组中进行“搜索” ,如下所示

"reservations": [
 {
    "campsiteId": 1, 
    "startDate": "2016-06-01", 
    "endDate": "2016-06-04", 
     "searchStartDate": "2016-06-07, 
     "searchEndDate": "2016-06-10
 },
 {
    "campsiteId": 1, 
    "startDate": "2016-06-11", 
    "endDate": "2016-06-13",
    "searchStartDate": "2016-06-07, 
    "searchEndDate": "2016-06-10
 },
 {
   "campsiteId": 2, 
   "startDate": "2016-06-08", 
   "endDate": "2016-06-09",
   "searchStartDate": "2016-06-07, 
   "searchEndDate": "2016-06-10
 }

In the example above I have the search object added to each index of the reservations array. 在上面的示例中,我将搜索对象添加到了预订数组的每个索引中。

I was hoping it was a matter of concatenating or mapping to transform the array. 我希望可以通过级联或映射来转换数组。 However, I am not able to get inside of each index on the reservations array 但是,我无法进入预留数组中的每个索引

Any insight into navigating this json object would be greatly appreciated. 任何对导航此json对象的见解将不胜感激。

Not sure why you cannot get "inside each index", but you don't have to and you can even do this without RxJS: 不知道为什么不能在“每个索引内”,但是您不必这样做,甚至可以在没有RxJS的情况下执行此操作:

.map((response: Response) => response.json()) // <IProduct[]>
  .map((tripDate) => ({
    reservations: tripDate.reservations
      .map(reservation => Object.assign(
        {},
        reservation,
        {
          searchStartDate: tripDate.search.startDate,
          searchEndDate: tripDate.search.endDate
        }
      )
    )
  }))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM