【问题标题】:How to extract 2 properties from an array of objects as an observabe?如何从对象数组中提取 2 个属性作为可观察对象?
【发布时间】:2018-06-08 04:48:29
【问题描述】:

我有一个可观察的对象数组,如下所示:

[
  {
    id: 1,
    name: "New York",
    latitude: 15.5539737,
    longitude: -78.5989487
  },
  {
    id: 2,
    name: "Chicago",
    latitude: 55.5539737,
    longitude: 28.5989487
  },
  {
    id: 3,
    name: "Los Angeles",
    latitude: 95.5539737,
    longitude: -72.587
  }
]

如何返回一个新的可观察对象数组,只提取其中的两个属性(纬度和经度)?

【问题讨论】:

  • 数组只包含3个对象还是可变数量的对象?
  • 变量。我保持示例数组简洁

标签: rxjs observable rxjs5


【解决方案1】:

你可以先使用 RxJS 中的 map 操作符,然后使用 Array 中的 map,如下:

// first use the map operator from RxJS    
    YourObservable.map(x=>{
    // then use Array.prototype.map
        x.map(return {longiture:x.longitude, latitude:x.latitude})
        })

不要混淆上面使用的两个映射,one 来自 RxJS,other 来自 Array,两者完全不同。

另外注意,如果使用RxJS6,需要使用管道如下:

 YourObservable.pipe(
     map(x=>{
           x.map(return {longiture:x.longitude, latitude:x.latitude})
        }))

【讨论】:

    【解决方案2】:
    const arr = [
      {
        id: 1,
        name: "New York",
        latitude: 15.5539737,
        longitude: -78.5989487
      },
      {
        id: 2,
        name: "Chicago",
        latitude: 55.5539737,
        longitude: 28.5989487
      },
      {
        id: 3,
        name: "Los Angeles",
        latitude: 95.5539737,
        longitude: -72.587
      }
    ]
    
    const example2= from(arr).pipe(map(a => {
      return {latitude: a.latitude, longitude: a.longitude,}
    }));
    const subscribe = example2.subscribe(val => console.log(val));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多