BardsWork
BardsWork

Reputation: 566

node map and filter results into new array

I'm having a brain fart, can someone point me in the right direction please.

Objective: Taking rows from a query, format the rows into new arrays of coordinates with ID as the index.

Example response from query: This is an array of objects, returned from mysql query. Cleared up possible confusion.

[
    {
        id: 2031,
      store_id: 12,
      latitude: '40.734479',
      longitude: '-73.998943' 
    },
    {
        id: 2041,
        store_id: 12,
      latitude: '40.732912',
      longitude: '-74.000083' 
    },
    {
        id: 2051,
      store_id: 14,
      latitude: '40.731053',
      longitude: '-74.001423' 
    },
    {
        id: 2061,
        store_id: 14,
        latitude: '40.729696',
        longitude: '-74.002186' 
    },
    {
        id: 2071,
        store_id: 14,
        latitude: '40.729121',
        longitude: '-74.002473' 
    }
]

Desired output:

{
    12:[
        { latitude: '40.734479', longitude: '-73.998943' },
        { latitude: '40.732912', longitude: '-74.000083' }
    ],

    14:[
        { latitude: '40.731053', longitude: '-74.001423'},
        { latitude: '40.729696', longitude: '-74.002186'},
        { latitude: '40.729121', longitude: '-74.002473'}
    ]
}   

Previously, utilizing a for loop, I've checking if object had property, then creating property if not, then populated the arrays.

Is there a better way to achieve this with map and reduce and/or filter?

Thanks.

Upvotes: 2

Views: 63

Answers (1)

CRice
CRice

Reputation: 32176

You can achieve this with Array.reduce:

const myArr = [{
  id: 2031,
  store_id: 12,
  latitude: '40.734479',
  longitude: '-73.998943' 
}, {
  id: 2041,
  store_id: 12,
  latitude: '40.732912',
  longitude: '-74.000083' 
}, {
  id: 2051,
  store_id: 14,
  latitude: '40.731053',
  longitude: '-74.001423' 
}, {
  id: 2061,
  store_id: 14,
  latitude: '40.729696',
    longitude: '-74.002186' 
}, {
  id: 2071,
  store_id: 14,
  latitude: '40.729121',
  longitude: '-74.002473' 
}];

const merged = myArr.reduce((merged, item) => {
  if (!merged[item.store_id]) merged[item.store_id] = [];
  merged[item.store_id].push({
    latitude: item.latitude,
    longitude: item.longitude,
  });

  return merged;
}, {});

console.log(merged)

Upvotes: 3

Related Questions