如何从对象数组中提取 2 个属性作为可观察对象?

How to extract 2 properties from an array of objects as an observabe?

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

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

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

可以先使用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 is from RxJS and the other来自Array,两者完全不同。

另请注意,如果使用RxJS6,需要使用pipe如下:

 YourObservable.pipe(
     map(x=>{
           x.map(return {longiture:x.longitude, latitude:x.latitude})
        }))
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));