如何从数组中提取经纬度对象并将其推入新数组

时间:2020-07-29 12:54:24

标签: javascript arrays react-native object

我有很多客户,我只想提取每个客户的经度和纬度,并且我想得到这样的客户

latLong=[{lat:123,long:322},{lat:111,long:333},{lat:33,long:11}]

这是我的客户数组,我只想从每个对象中提取经纬度,然后将它们放入对象数组中。

  "customers": [
        {
            "id": "5",
            "aname": "Sts Customers",
            "type": "2",
            "address": "house no e 4",
            "area_id": "7",
            "cell_no": "03334488",
            "opn_type": "Debit",
            "opngbl": "2564",
            "lat": "33.7997",
            "longi": "73.04052769999998",
            "company_id": "1",
            "acct_no": ""
        },
        {
            "id": "14",
            "aname": "New Customer",
            "type": "2",
            "address": "house no 4",
            "area_id": "8",
            "cell_no": "7878",
            "opn_type": "Credit",
            "opngbl": "2541",
            "lat": "33.7997",
            "longi": "73.04052769999998",
            "company_id": "1",
            "acct_no": ""
        },
        {
            "id": "15",
            "aname": "one more customer",
            "type": "2",
            "address": "jjkhklj",
            "area_id": "8",
            "cell_no": "8876987",
            "opn_type": "Credit",
            "opngbl": "454",
            "lat": "33.7997",
            "longi": "73.04052769999998",
            "company_id": "1",
            "acct_no": ""
        }
    ],

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作。

const source = {
  customers: [
{
  id: '5',
  aname: 'Sts Customers',
  type: '2',
  address: 'house no e 4',
  area_id: '7',
  cell_no: '03334488',
  opn_type: 'Debit',
  opngbl: '2564',
  lat: '33.7997',
  longi: '73.04052769999998',
  company_id: '1',
  acct_no: '',
},
{
  id: '14',
  aname: 'New Customer',
  type: '2',
  address: 'house no 4',
  area_id: '8',
  cell_no: '7878',
  opn_type: 'Credit',
  opngbl: '2541',
  lat: '33.7997',
  longi: '73.04052769999998',
  company_id: '1',
  acct_no: '',
},
{
  id: '15',
  aname: 'one more customer',
  type: '2',
  address: 'jjkhklj',
  area_id: '8',
  cell_no: '8876987',
  opn_type: 'Credit',
  opngbl: '454',
  lat: '33.7997',
  longi: '73.04052769999998',
  company_id: '1',
  acct_no: '',
},
  ],
};

const result = source.customers.map(({ lat, longi: long }) => ({ lat, long }));

console.log(result);

基本上,我们可以使用map遍历source.customers数组。

然后我们将传递给回调的customer对象解构以仅选择latlongi,将longi重命名为long

最后,我们返回一个仅包含我们感兴趣的键值对的对象。