如何从一个对象数组中提取2个属性作为observabe?

时间:2018-06-08 04:48:29

标签: rxjs observable rxjs5

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

[
  {
    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
  }
]

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

2 个答案:

答案 0 :(得分:3)

您可以先使用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来自数组,两者完全不同。

另请注意,如果使用RxJS6,则需要使用管道,如下所示:

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

答案 1 :(得分:0)

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));
相关问题