繁体   English   中英

如何获取数组内的 object 的多个键

[英]How can I get multiple keys of an object that are inside an array

我一直在尝试找到与我需要做的类似的事情,但我还没有完全找到它。

我有一个像这样的对象数组

const places = [
  {
    City: 'Tribuckan',
    Lat: 48569.52,
    Long: 48.5
  },
  {
    City: 'Mecca',
    Lat: 48569.52,
    Long: 48.5
  },
    {
    City: 'Dazenda',
    Lat: 48569.52,
    Long: 48.5
  },
    {
    City: 'Uzumakin',
    Lat: 48569.52,
    Long: 48.5
  },
];

我想从每个 object 中获取纬度和经度并返回它们,以便它们可以在单独的 function 中使用,这将计算出与原始 object 的距离以分隔坐标客户端。

我的理论是,我需要将每个 object 从数组中分离出来,并将其发送到 function ,后者将存储坐标并将它们与客户端坐标进行比较。

这是我尝试过的,但它不起作用,所以我认为我离基地很远。

 const places = [ { City: 'Tribuckan', Lat: 48569.52, Long: 48.5 }, { City: 'Mecca', Lat: 48569.52, Long: 48.5 }, { City: 'Dazenda', Lat: 48569.52, Long: 48.5 }, { City: 'Uzumakin', Lat: 48569.52, Long: 48.5 }, ]; const firstFun = (places) => { places.forEach(obj => funTest(obj)); } const funTest = (obj) => { let Lat = obj.Lat; let Lon = obj.Long; compare(lat, lon); } const compare = (lat, lon, GUESTLAT, GUESTLON) => { let newLat = GUESTLAT - lat; let newLong = GUESTLON = lon }

使用Array.prototype.map function 应该可以得到您正在寻找的结果。 下面是一个例子。

const places = [
  {
    City: 'Tribuckan',
    Lat: 48569.52,
    Long: 48.5
  },
  {
    City: 'Mecca',
    Lat: 48569.52,
    Long: 48.5
  },
    {
    City: 'Dazenda',
    Lat: 48569.52,
    Long: 48.5
  },
    {
    City: 'Uzumakin',
    Lat: 48569.52,
    Long: 48.5
  },
];

const compareLatLong = (locationObject, guestLat, guestLong) => {
  return {
    Lat: locationObject.Lat - guestLat,
    Long: locationObject.Long - guestLong
  }
}

const guestLatitude = 1;
const guestLongitude = 1;

const getLatLongCompared = places.map(locationObject => {
  return compareLatLong({
    Lat: locationObject.Lat,
    Long: locationObject.Long
  }, guestLatitude, guestLongitude);
});

console.log(getLatLongCompared);

根据我的理解,您有一个访客位置 object 及其latlong ,您想根据places数组中的位置过滤掉 object 并更新latlong 如果是,这里是 go

 // Input places array const places = [ { City: 'Tribuckan', Lat: 48569.52, Long: 48.5 }, { City: 'Mecca', Lat: 48569.52, Long: 48.5 }, { City: 'Dazenda', Lat: 48569.52, Long: 48.5 }, { City: 'Uzumakin', Lat: 48569.52, Long: 48.5 } ]; // Guest location object with different lat and long const guestLocationObj = { City: 'Mecca', Lat: 55000.80, Long: 62.7 }; // Filtered out the object from places array based on the user location. const filteredObject = places.find(({ City }) => City === guestLocationObj.City); // Calculate the lat and long const guestLat = guestLocationObj.Lat - filteredObject.Lat; const guestLong = guestLocationObj.Long - filteredObject.Long; // final output console.log(guestLat, guestLong);

暂无
暂无

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

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