var date = new Date('2010-10-11T00:00:00+05:30');
console.log( ((date.getMonth() > 8) ? (date.getMonth() + 1) : ('0' + (date.getMonth() + 1))) + '/' + ((date.getDate() > 9) ? date.getDate() : ('0' + date.getDate())) + '/' + date.getFullYear() );

 

 

출처: https://stackoverflow.com/questions/11591854/format-date-to-mm-dd-yyyy-in-javascript

'Client Standard > JavaScript & jQuery' 카테고리의 다른 글

[js] delete obj.key  (0) 2020.10.22
[Javascript] date sorting  (0) 2020.06.30
[Js] 배열 정렬  (0) 2019.09.06
[Tag] br 태그 줄바꿈  (0) 2019.02.07
[Ajax] 콜 이후 obj append  (0) 2019.01.25

const o = { lastName: 'foo' }

o.hasOwnProperty('lastName') // true

delete o['lastName']

o.hasOwnProperty('lastName') // false

'Client Standard > JavaScript & jQuery' 카테고리의 다른 글

[Javascript] Format date to MM/dd/yyyy  (0) 2021.08.24
[Javascript] date sorting  (0) 2020.06.30
[Js] 배열 정렬  (0) 2019.09.06
[Tag] br 태그 줄바꿈  (0) 2019.02.07
[Ajax] 콜 이후 obj append  (0) 2019.01.25

sortedRecents.sort((ab=> new Date(b.regDt) - new Date(a.regDt))

'Client Standard > JavaScript & jQuery' 카테고리의 다른 글

[Javascript] Format date to MM/dd/yyyy  (0) 2021.08.24
[js] delete obj.key  (0) 2020.10.22
[Js] 배열 정렬  (0) 2019.09.06
[Tag] br 태그 줄바꿈  (0) 2019.02.07
[Ajax] 콜 이후 obj append  (0) 2019.01.25

/* sortingNumber() : 숫자인 실수만으로 되어있을 때, 적용될 함수 */ 
function sortingNumber( a , b ){  

        if ( typeof a == "number" && typeof b == "number" ) return a - b; 

        // 천단위 쉼표와 공백문자만 삭제하기.  
        var a = ( a + "" ).replace( /[,\s\xA0]+/g , "" ); 
        var b = ( b + "" ).replace( /[,\s\xA0]+/g , "" ); 

        var numA = parseFloat( a ) + ""; 
        var numB = parseFloat( b ) + ""; 

        if ( numA == "NaN" || numB == "NaN" || a != numA || b != numB ) return false; 

        return parseFloat( a ) - parseFloat( b ); 
}

/* changeForSorting() : 문자열 바꾸기. */ 
function changeForSorting( first , second ){  

        // 문자열의 복사본 만들기. 
        var a = first.toString().replace( /[\s\xA0]+/g , " " ); 
        var b = second.toString().replace( /[\s\xA0]+/g , " " ); 

        var change = { first : a, second : b }; 

        if ( a.search( /\d/ ) < 0 || b.search( /\d/ ) < 0 || a.length == 0 || b.length == 0 ) return change; 

        var regExp = /(\d),(\d)/g; // 천단위 쉼표를 찾기 위한 정규식. 

        a = a.replace( regExp , "$1" + "$2" ); 
        b = b.replace( regExp , "$1" + "$2" ); 

        var unit = 0; 
        var aNb = a + " " + b; 
        var numbers = aNb.match( /\d+/g ); // 문자열에 들어있는 숫자 찾기 

        for ( var x = 0; x < numbers.length; x++ ){ 

                var length = numbers[ x ].length; 
                if ( unit < length ) unit = length; 
        } 

        var addZero = function( string ){ // 숫자들의 단위 맞추기 

                var match = string.match( /^0+/ ); 

                if ( string.length == unit ) return ( match == null ) ? string : match + string; 

                var zero = "0"; 

                for ( var x = string.length; x < unit; x++ ) string = zero + string; 

                return ( match == null ) ? string : match + string; 
        }; 

        change.first = a.replace( /\d+/g, addZero ); 
        change.second = b.replace( /\d+/g, addZero ); 

        return change; 
}

/*    ordinary() 
 * 
 * 1. ascending : 오름차순 
 * 2. descending : 내림차순 
*/ 
function ordinary(){ 

        var compare = function( a , b ){ 

                var sorting = sortingNumber( a , b ); 

                if ( typeof sorting == "number" ) return sorting; 

                var change = changeForSorting( a , b ); 

                var a = change.first; 
                var b = change.second; 

                return ( a < b ) ? -1 : ( a == b ) ? 0 : 1; 
        }; 

        var ascendingOrder = function( a , b ){  return compare( a , b );  }; 
        var descendingOrder = function( a , b ){  return compare( b , a );  }; 

        return { ascending : ascendingOrder, descending : descendingOrder }; 
}

/*    ignoreCase() : 대소문자 무시 ( toLowerCase ) 
 * 
 * 1. ascending : 오름차순 
 * 2. descending : 내림차순 
*/ 
function ignoreCase(){ 

        var compare = function( a , b ){ 

                var sorting = sortingNumber( a , b ); 

                if ( typeof sorting == "number" ) return sorting; 

                var change = changeForSorting( a , b ); 

                var a = change.first.toLowerCase(); 
                var b = change.second.toLowerCase(); 

                return ( a < b ) ? -1 : ( a == b ) ? 0 : 1;   // 또는,  return a.localeCompare ( b );
        }; 

        var ascendingOrder = function( a , b ){  return compare( a , b );  }; 
        var descendingOrder = function( a , b ){  return compare( b , a );  }; 

        return { ascending : ascendingOrder, descending : descendingOrder }; 
}

/*    byLocale() : 로컬에 따라 ( localeCompare ) - 언어에 따라, 결과가 다를 수 있음. 
 * 
 * 1. ascending : 오름차순 
 * 2. descending : 내림차순 
*/ 
function byLocale(){ 

        var compare = function( a , b ){ 

                var sorting = sortingNumber( a , b ); 

                if ( typeof sorting == "number" ) return sorting; 

                var change = changeForSorting( a , b ); 

                var a = change.first; 
                var b = change.second; 

                return a.localeCompare( b ); 
        }; 

        var ascendingOrder = function( a , b ){  return compare( a , b );  }; 
        var descendingOrder = function( a , b ){  return compare( b , a );  }; 

        return { ascending : ascendingOrder, descending : descendingOrder }; 
}

 

 

 

// 실제 소스

var selectObj = $('#sortOrdr');
var order = ordinary(); // js 순서정렬 공통함수

var originSortOrdr = [];
var domnSortOrdr = [];

$.each(result.domnList, function(index, item){
originSortOrdr.push(item.sortOrdr);
});

// sortOrdr 순차 정렬
domnSortOrdr = originSortOrdr.sort( order.ascending );

selectObj.empty();

$.each(domnSortOrdr, function(index, item){
var option = $("" + item + "");
if(item == treeNode.sortOrdr)
option = $("" + item + "")
selectObj.append(option);
});

 

 

 

출처: https://tonks.tistory.com/117

DEPRECATED

This is the checklist of ways to improve WebStorm(PhpStorm, Idea, etc.) experience:

  1. Use Vue.js plugin.

UPDATE: Both plugins have own problems atm

You can install it via Settings(Preferences) => Plugins => Browse repositories => (search for) "vue"

choose one or both: "Vue.js" or "vue-for-idea". It's up to you.

  1. Set "Javascript Language Version" to ES6.

Open Settings(Preferences) => Language & Frameworks => JavaScript. Set Javascript Language Version to ECMAcript6

https://github.com/postalservice14/vuejs-plugin

  1. Improve HTML-tag's attributes highlighting

Open Settings(Preferences) => Editor => Inspection => HTML => select Unknown HTML tag attributes => click Custom HTML tag attributes. Add your attributes. 

For example, my list: 

v-on,v-on:click,v-on:change,v-on:focus,v-on:blur,v-on:keyup,:click,@click,v-model,v-text,v-bind,:disabled,@submit,v-class,:class,v-if,:value,v-for,scoped,@click.prevent,number,:readonly,@input,@click,v-show,v-else,readonly,v-link,:title,:for,tab-index,:name,:id,:checked,transition,@submit.prevent,autocapitalize,autocorrect,slot,v-html,:style

P.S. For the full list of custom tags check @Alex's answer below

P.P.S. Actually it's should work in more common way:

Open Settings(Preferences) => Languages & Frameworks => Javascript => Libraries=> click Add (after this you should set path to the vue.js. You can dowmload it with npm or whatever)

(More info in this answer: https://stackoverflow.com/a/28903910/930170)

But I didn't get success with that.

  1. Enable Node.js Coding Assistance:

Open Settings(Preferences) => Languages & Frameworks => Node.js and NPM

If "Node.js core library is not enabled", click button Enabled


DEPRECATED (may be required if you don't use vue plugins for IDE):

  1. Make *.vue files to be recognized as a html flies.

Open Settings(Preferences) => Editor =>File Types find HTML in Recognized File Types, then add *.vue as a new Registered Patterns.

  1. Improve ES6 highlight.

In each vue file with tag:

(This is would help to recognise constructions like setTimeout(() => {console.log(1) }, 100))

  1. Improve styles highlight. (sass, scss, etc)

In each vue file with tag:

For scss it's gonna be <style lang="scss" type="text/scss">

For stylus please try <style lang="stylus" type="text/stylus">


UPD: The steps below are not so trusted, they may helps, or may not, some of them I didn't check personally, or I didn't catch is any effect exist or not.

  1. Import TextMate Bundle functionality.

https://www.jetbrains.com/help/phpstorm/2016.1/textmate-bundles.html?origin=old_help

  1. Import TypeScript tables for vue.

Open Settings(Preferences) => Language & Frameworks => JavaScript => Libraries. Click Download, Switch to TypeScript community stubs. And download all tabs with vueword.

Example: https://youtu.be/4mKiGkokyx8?t=84 (from 1:24)


UPD2: For more info check the issue at github: https://github.com/vuejs/vue-syntax-highlight/issues/3

 

출처: https://nickjoit.tistory.com/155 [nickjoIT]

.replace(/(<br>|<br\/>|<br \/>)/g, '\r\n')


var tbodyObj = $('#medicalProcess');

if(data != null && data.length > 0) {
$.each(data, function(idx, item) {
var trObj = $("<tr></tr>");
var tdObj = $("<td></td>");

trObj.append(tdObj.clone().append(item.b_reqDate));
trObj.append(tdObj.clone().append(item.b_infoOpen));
trObj.append(tdObj.clone().append(item.b_name));
trObj.append(tdObj.clone().append(item.b_patmas));

// aObj.attr("onclick","fnSetRoadDetailList('"+item.city+"','"+item.gu+"','"+item.dong+"','"+item.roadNm+"','"+item.dongNm+"');$('#goDoroStep_3').focus();return false;");
// aObj.text(item.roadAddr);
tbodyObj.append(trObj);
});
} else {
var trObj = $("<tr></tr>");
var tdObj = $("<td></td>");
tbodyObj.append(trObj.append(tdObj.append("조회된 내역이 없습니다.")));
}


Request Body로 보내지는 JSON의 행방 불명

문제

api 테스트 시 Postman을 자주 사용하는데, 다음과 같이 JSON을 서버에 보내면,

Imgur

서버의 Request에서 JSON 정보를 찾을 수 없다.

Imgur

해결

하지만 동일한 json 데이터를 postman이 아니라 다음과 같이 실제로 ajax로 호출하는 코드를 통해 서버로 보내면 서버의 Request에서 JSON 정보가 잘 나온다.

<html>
<body>
<button id='tester'>JSON Request Test</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
var tester = document.getElementById('tester');
tester.addEventListener('click', function(e) {
	(function($) {
	    $.ajax({
	        url: 'http://---------/v1/logs/view/33/55',
//	        contentType: 'application/json',
	        method: 'POST',
	        crossDomain: true,
	        data: {
	            url: "++++++++++++++++++++++++++++++++++++",
	            ref: "====================================",
	            items: [
	                {id: "1198708089",
	                title:"나이키 에어맥스",
	                image:"%%%%%%%%%%%%%%%%%%%%%/1197829883_B_V2.jpg",
	                price: 12000,
	                currency:"KRW",
	                catalog: ["catalog_id"],
	                is_now_delivery: 0,
	                adult_only: 0,
	                is_hidden: 0}
	            ],
	            user: { gender: "F", birthyear:"1980", mid:"8371920381"}
	        }
	    });
	})(jQuery);
});
</script>
</body>
</html>

둘의 결정적인 차이는 ContentType 헤더의 값이다.

Postman에서 보낼 떄는 ContentType을 application/json으로 보냈고, 그 때문에 request에서 찾을 수 없었다.

jQuery의 ajax로 보낼 때 ContentType을 명시하지 않으면 디폴트로 application/x-www-form-urlencoded; charset=UTF-8로 지정되며(여기 참고), Request 요청을 브라우저에서 살펴봐도 아래와 같이 Request Body에 포함되고,

Imgur

서버의 Request에서도 확인이 가능하다.

Imgur

진짜 해결 맞아?

서버에서 읽힌다고는 하지만, 아무리 그래도 데이터를 JSON으로 넘기는데, ContentType을 application/json이 아닌 application/x-www-form-urlencoded; charset=UTF-8으로 주는 건 좀 아닌 것 같다.

그렇다고 ContentType을 강제로 application/json으로 주면 요청은 아래와 Form Data가 아니라 Payload로 날라가므로,

Imgur

서버에서는 아래와 같이 request.getParameterMap()으로는 읽을 수 없고,

Imgur

대신 아래와 같이 request.getReader()로는 읽을 수 있다.

Imgur

하지만 이걸 사용하려면 또 parsing을 해야하고, stream에서는 한 번만 읽을 수 있는 등 불편한점이 많아서 실무적이지 않다.

실무에서는?

실제로는 request를 직접 핸들링하는 방식 대신에 DTO를 만들고 request 안에 json으로 넘어온 정보를 Jackson 같은 라이브러리를 써서 DTO에 집어넣는 방식을 택한다.

이때 프론트쪽에서 주의해야할 것이 있는데, jQuery의 ajax는 데이터를 문자열화 해주지 않기 때문에 아래와 같이 보내면,

$.ajax({
    url: 'http://---------/v1/logs/view/33/55',
    contentType: 'application/json',
    method: 'POST',
    crossDomain: true,
    data: {
        url: "++++++++++++++++++++++++++++++++++++",
        ref: "====================================",
        items: [
            {id: "1198708089",
            title:"나이키 에어맥스",
            image:"%%%%%%%%%%%%%%%%%%%%%/1197829883_B_V2.jpg",
            price: 12000,
            currency:"KRW",
            catalog: ["catalog_id"],
            is_now_delivery: 0,
            adult_only: 0,
            is_hidden: 0}
        ],
        user: { gender: "F", birthyear:"1980", mid:"8371920381"}
    }
});

서버에서는 대략 아래와 같은 에러가 발생한다.

org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Unrecognized token 'url': was expecting ('true', 'false' or 'null')

이는 url이 JSON 객체 내의 key로 인식되지 않기 때문에 발생하는 문제로서, 이를 방지하려면 다음과 같이 JSON.stringify()를 통해 url이 key로 인식될 수 있도록 "url"와 같이 문자열로 만들어서 보내줘야 한다.

$.ajax({
    url: 'http://---------/v1/logs/view/33/55',
    contentType: 'application/json',
    method: 'POST',
    crossDomain: true,
    data: JSON.stringify({
        url: "++++++++++++++++++++++++++++++++++++",
        ref: "====================================",
        items: [
            {id: "1198708089",
            title:"나이키 에어맥스",
            image:"%%%%%%%%%%%%%%%%%%%%%/1197829883_B_V2.jpg",
            price: 12000,
            currency:"KRW",
            catalog: ["catalog_id"],
            is_now_delivery: 0,
            adult_only: 0,
            is_hidden: 0}
        ],
        user: { gender: "F", birthyear:"1980", mid:"8371920381"}
    })
});

서버에서도 Spring을 예로 들면, controller 메서드의 파라미터에 JSON으로 받을 데이터를 매핑할 수 있는 DTO를 추가하고 앞에 @RequestBody를 꼭 붙여줘야 데이터가 DTO에 정상적으로 입력된다.

진짜 해결

  • 프론트: JSON 데이터를 application/json으로 보내되, JSON 객체를 JSON.stringify()로 문자열화 해서 서버에 보내야 한다.

  • 스프링 백엔드: JSON 데이터와 구조가 같은 DTO를 만들고, 컨트롤러 메서드에 @RequestBody를 붙여서 DTO를 파라미터에 추가하면 Spring이 Jackson을 통해 JSON의 값을 읽어서 DTO에 잘 넣어준다.



출처: https://github.com/HomoEfficio/dev-tips/blob/master/Request%20Body%EB%A1%9C%20%EB%B3%B4%EB%82%B4%EC%A7%80%EB%8A%94%20JSON%EC%9D%98%20%ED%96%89%EB%B0%A9%20%EB%B6%88%EB%AA%85.md


'Client Standard > JavaScript & jQuery' 카테고리의 다른 글

[Tag] br 태그 줄바꿈  (0) 2019.02.07
[Ajax] 콜 이후 obj append  (0) 2019.01.25
[jQuery] JSON 으로 Highcharts 구현  (0) 2018.05.15
[JSON] json-groupby 관련  (0) 2017.06.23
[Javascript] 뒤로가기 체크 여부  (0) 2017.03.06

JSON 파일에 RAW성 데이터를 담아 두고,(참고로 데이터는 가짜 데이터입니다.)

이 데이터들을 조작(필터링과 그룹핑)하여 차트에 그려준 후(column, line, pie차트), 테이블에 출력하는 예제입니다.

차트는 HighChart 라이브러리를 사용하였고, 

IE 8이상에서는 html파일을 실행하면 바로 출력되지만 크롬에서는 AJAX 통신을 하므로 압축을 푼 후 웹서버에 올려서 실행하면 됩니다.

자세한 내용은 소스코드의 주석을 참고하시기 바랍니다.


highcharts_hw.zip



출처: http://egloos.zum.com/tit99hds/v/3441566

사정 상 데이터를 가공한 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