사정 상 데이터를 가공한 JSON으로 통계를 만들었는데요.


아시다시피 JOSN은 데이터를 뿌릴떄나, 간단한 정렬정도는 가능하였습니다.

속도도 빠르구요.

단  통계데이터 중 예외적으로 Group by 해야 할 데이터가 생겨 난감했습니다.

ex. [{A회사..}, {B회사..}, {B회사..}]

 => A회사 , B회사


물론 열심히 each문을 돌려서 그룹화 하는것도 있지만. 구글에서 검색결과


JSON 파일을 GroupBy 해주는 함수 라이브러리를 찾았습니다.


라이센스는MIT라 자유롭게 쓸수있는것으로 보이고, 저의 경우는 다이렉트로 파일을 가져와 사용했습니다.

개발환경에 맞게 수정을 해야합니다.

저의 경우 json-groupby.js

맨 하단 module.exports = groupBy  절을 주석걸어 사용하였습니다.



여러예제가 있지만.. .가장 간단한 예제로 설명하겠습니다.


원본 JSON배열

var products = 
 [{"id": 1,
   "product": "ri", "price": 16, "color": "green", "available": false,
   "tags": ["bravo"],
   "vendor": {"name": "Donald Chambers", "address": {"city": "Mumbai"}}},
  {"id": 2,
   "product": "foef", "price": 44, "color": "yellow", "available": false,
   "tags": ["alpha"],
   "vendor": {"name": "Barbara Garrett", "address": {"city": "Mumbai"}}},



* products =  JSON원본(배열)

* color = GropuBY할 컬럼(키)

* id = Group 소속된  컬럼(배열)


헤당 메서드 호출 시

groupBy(products, ['color'], ['id'])


OUTPUT

{ green: { id: [ 1, 5, 6, 7, 8 ] },
  yellow: { id: [ 2, 4 ] },
  red: { id: [ 3 ] } }






---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------






참고: https://github.com/gagan-bansal/json-groupby

내용:



json-groupby

Group array of JOSN objects based on associated properties.

installation

npm install json-groupby

usage

var groupBy = require('json-groupby')
var group = groupBy(array, properties [, collect])
  • array Array of JSON objects

  • properties Array JSON properties' path like address.city or lookup object

    lookup

    {
      intervals: array of numbers
      ,property: string
      [,labels: array of string]
    }
    

    intervals Array of intervals. Like [ 10, 20, 30, 40, 50] group the data in four ranges, whereas lower bound is inclusive and upper bound is exclusive.

    peroperty Property path like price

    labels Array of interval labels like [ 'low', 'medium', 'high']

  • collect Array of properties that need to be collected in array

examples

data set
var products = 
 [{"id": 1,
   "product": "ri", "price": 16, "color": "green", "available": false,
   "tags": ["bravo"],
   "vendor": {"name": "Donald Chambers", "address": {"city": "Mumbai"}}},
  {"id": 2,
   "product": "foef", "price": 44, "color": "yellow", "available": false,
   "tags": ["alpha"],
   "vendor": {"name": "Barbara Garrett", "address": {"city": "Mumbai"}}},
  {"id": 3,
   "product": "jehnojto", "price": 29, "color": "red", "available": true,
   "tags": ["alpha"],
   "vendor": {"name": "Anne Leonard", "address": {"city": "New York"}}},
  {"id": 4,
   "product": "ru", "price": 35, "color": "yellow", "available": false,
   "tags": ["echo", "charlie", "bravo"],
   "vendor": {"name": "Justin Doyle", "address": {"city": "London"}}},
  {"id": 5,
   "product": "pihluve", "price": 47, "color": "green", "available": true,
   "tags": ["delta", "echo", "bravo"],
   "vendor": {"name": "Emily Abbott", "address": {"city": "New York"}}},
  {"id": 6,
   "product": "dum", "price": 28, "color": "green", "available": true,
   "tags": ["echo", "delta", "charlie"],
   "vendor": {"name": "Henry Peterson", "address": {"city": "New York"}}},
  {"id": 7,
   "product": "zifpeza", "price": 10, "color": "green", "available": false,
   "tags": ["echo", "charlie", "bravo"],
   "vendor": {"name": "Jesus Lowe", "address": {"city": "Mumbai"}}},
  {"id": 8,
   "product": "av", "price": 39, "color": "green", "available": true,
   "tags": ["bravo"],
   "vendor": {"name": "Rosalie Erickson", "address": {"city": "New York"}}}]
```

##### group by single property
```javascript
groupBy(products, ['color'], ['id'])
// output is 
{ green: { id: [ 1, 5, 6, 7, 8 ] },
  yellow: { id: [ 2, 4 ] },
  red: { id: [ 3 ] } }
```

##### group by many properties and without collect option
```javascript
groupBy(products, ['available', 'color', 'vendor.address.city'])
// output is 
{"false": 
  {"green": 
    {"Mumbai": [
      {"id": 1, "product": "ri", "price": 16, "color": "green", 
       "available": false, "tags": ["bravo"], 
       "vendor": {"name": "Donald Chambers",  "address": {"city": "Mumbai"}}},
      {"id": 7, "product": "zifpeza", "price": 10, "color": "green",
       "available": false, "tags": ["echo", "charlie", "bravo"],
       "vendor": {"name": "Jesus Lowe", "address": {"city": "Mumbai"}}}]},
   "yellow": {
     "Mumbai": [
       {"id": 2, "product": "foef", "price": 44, "color": "yellow", 
        "available": false, "tags": ["alpha"], 
        "vendor": {"name": "Barbara Garrett",  "address": {"city": "Mumbai"}}}], 
     "London": [
       {"id": 4, "product": "ru", "price": 35, "color": "yellow",
        "available": false, "tags": ["echo", "charlie", "bravo"],
        "vendor": {"name": "Justin Doyle", "address": {"city": "London"}}}]}},
 "true": 
  {"red": 
    {"New York": [
      {
        "id": 3, "product": "jehnojto", "price": 29, "color": "red",
        "available": true, "tags": ["alpha"],
        "vendor": {"name": "Anne Leonard", "address": {"city": "New York"}}}]},
   "green": {
     "New York": [
        {"id": 5, "product": "pihluve", "price": 47, "color": "green",
         "available": true, "tags": ["delta", "echo", "bravo"],
         "vendor": {"name": "Emily Abbott", "address": {"city": "New York"}}},
         {"id": 6, "product": "dum", "price": 28, "color": "green",
         "available": true, "tags": ["echo", "delta", "charlie"],
         "vendor": {"name": "Henry Peterson", "address": {"city": "New York"}}},
         {"id": 8, "product": "av", "price": 39, "color": "green",
         "available": true, "tags": ["bravo"],
         "vendor": {"name": "Rosalie Erickson", "address": {"city": "New York"}}}
     ]}}}
``` 

##### single deep path property 
```javascript
groupBy(products, ['vendor.address.city'], ['id'])
// output is 
{ Mumbai: { id: [ 1, 2, 7 ] },
  'New York': { id: [ 3, 5, 6, 8 ] },
  London: { id: [ 4 ] } }
```   
##### group with boolean property
```javascript
groupBy(products, ['available'], ['id'])
// output is 
{ false: { id: [ 1, 2, 4, 7 ] }, 
  true: { id: [ 3, 5, 6, 8 ] }}
```  

##### group by intervals (lookup of intervals) without intervals' name
```javascript 
groupBy(
  products, 
  [{property: 'price', intervals: [10,20,40,50]}],
  ['id'])
//output is 
{ '0': { id: [ 1, 7 ] },
  '1': { id: [ 3, 4, 6, 8 ] },
  '2': { id: [ 2, 5 ] } }
``` 

##### group by intervals (lookup of intervals) with intervals' lable name 
```javascript
groupBy(
  products, 
  [{
    property: 'price', 
    intervals: [10,20,40,50], 
    labels: ['low','medium','high']}],
  ['id'])
//ouptu is 
{'low': { id: [ 1, 7 ] },
 'medium': { id: [ 3, 4, 6, 8 ] },
 'high': { id: [ 2, 5 ] } }
```
##### group with mixed properties lookup and property path 
```javascript
groupBy(
  products, 
  [
    {
      property: 'price', 
      intervals: [10,20,40,50], 
      labels: ['low','medium','high']
    },
    'vendor.address.city'
  ],
  ['id'])
// output is
{
  "low":
    {"Mumbai":{"id":[1,7]}},
  "high":
    {"Mumbai":{"id":[2]},
    "New York":{"id":[5]}},
  "medium":
    {"New York":{"id":[3,6,8]},
    "London":{"id":[4]}}
```

##### group by tags that are in array 
```javascript
groupBy(products, ['tags'], ['id'])
//ouput is
{ bravo: { id: [ 1, 4, 5, 7, 8 ] },
  alpha: { id: [ 2, 3 ] },
  echo: { id: [ 4, 5, 6, 7 ] },
  charlie: { id: [ 4, 6, 7 ] },
  delta: { id: [ 5, 6 ] } }
```

##### group and collect many properties
```javascript
groupBy(
  products, 
  ['color'], 
  ['vendor.address.city', 'available'])
// output is
{ green: 
   { 'vendor.address.city': [ 'Mumbai', 'New York', 'New York', 'Mumbai', 'New York' ],
     available: [ false, true, true, false, true ] },
  yellow: 
   { 'vendor.address.city': [ 'Mumbai', 'London' ],
     available: [ false, false ] },
  red: { 'vendor.address.city': [ 'New York' ], available: [ true ] } }
```

## developing
Once you run
 
```npm isntall```

then for running test 

```npm run test```

to create build

```npm run build```

## license
This project is licensed under the terms of the MIT license.



+ Recent posts