Thursday, 16 March 2017

Mapping/organizing nested objects in node

I am trying to map nested objects myself without using something like JoinJS, which works great to an extent until I want to correctly make my JSON look pretty.

Based on the SQL query, my output is:

[
  {
    "id": 1,
    "city_name": "city 1 - some city name",
    "city_category": "city 1 - some category",
    "city_description": "city 1 - some city description",
    "city_id": 1,
    "store_id": 1
  },
  {
    "id": 1,
    "city_name": "city 1 - some city name",
    "city_category": "city 1 - some category",
    "city_description": "city 1 - some city description",
    "city_id": 1,
    "store_id": 2
  },
  {
    "id": 1,
    "city_name": "city 1 - some city name",
    "city_category": "city 1 - some category",
    "city_description": "city 1 - some city description",
    "city_id": 1,
    "store_id": 3
  },
  {
    "id": 2,
    "city_name": "city 2 - some city name",
    "city_category": "city 2 - some category",
    "city_description": "city 2 - some city description",
    "city_id": 2,
    "store_id": 1
  },
  {
    "id": 2,
    "city_name": "city 2 - some city name",
    "city_category": "city 2 - some category",
    "city_description": "city 2 - some city description",
    "city_id": 2,
    "store_id": 2
  }
]

I am trying to make this output look like this:

[
  {
    "city_id": 1,
    "city_name": "city 1 - some city name",
    "city_category": "city 1 - some category",
    "city_description": "city 1 - some city description",
    "store_ids": [1,2,3]
  }
  {
    "city_id": 2,
    "city_name": "city 2 - some city name",
    "city_category": "city 2 - some category",
    "city_description": "city 2 - some city description",
    "store_ids": [1,2]
  }
]

Using Lodash or just plain JS (no other modules like JoinJS, unless they are efficient for things like this), how would I manipulate this??



via Thomas Gorczynski

No comments:

Post a Comment