투케이2K

115. (javascript/자바스크립트) findIndex 사용해 특정 JSON KEY 값을 포함하는 데이터 확인 실시 - new Object , new Array 본문

JavaScript

115. (javascript/자바스크립트) findIndex 사용해 특정 JSON KEY 값을 포함하는 데이터 확인 실시 - new Object , new Array

투케이2K 2021. 8. 27. 07:41
반응형

[개발 환경 설정]

개발 툴 : Edit++

개발 언어 : javascript


[소스코드]

    <!-- 내부 JS 스타일 지정 -->
    <script>

       /*
       [JS 요약 설명]
       1. window onload : 웹 브라우저 로딩 완료 상태를 나타냅니다
       2. new Array : 배열 형태로 데이터를 저장합니다
       3. new Object : 오브젝트 형태로 데이터를 저장합니다 (json 가능)
       4. findIndex : 찾으려는 데이터를 포함하고 있는 인덱스 값을 반환합니다 (0부터 시작 / 없으면 -1값)
       */


       /* [html 최초 로드 및 이벤트 상시 대기 실시] */
       window.onload = function() {
          console.log("");
          console.log("[window onload] : [start]");
          console.log("");    

          // 이벤트 수행 함수를 호출
          runFunction();
       };

       

       /* [이벤트 수행 함수] */
       function runFunction(){
          console.log("");
          console.log("[runFunction] : [start]");
          console.log("");  

          // [json array 생성 실시]
          var jsonArray = new Array();


          // [new Object 사용해 json 객체 생성 실시]
          var jsonObjOne = new Object();
          jsonObjOne["idx"] = 1; 
          jsonObjOne["name"] = "twok"; 


          // [new Object 사용해 json 객체 생성 실시]
          var jsonObjTwo = new Object();
          jsonObjTwo["idx"] = 2; 
          jsonObjTwo["name"] = "투케이"; 


          // [json array 에 데이터 삽입 실시]
          jsonArray.push(jsonObjOne);
          jsonArray.push(jsonObjTwo);


          // [json array 에 저장된 데이터 확인]
          console.log("");
          console.log("[runFunction] : [jsonArray] : " + JSON.stringify(jsonArray));
          console.log("");  


          // [특정 key 값 데이터 확인 실시 : 없을 경우 -1 값 반환 : 데이터 포함 시 0 부터 시작해서 인덱스값 반환]
          // [주의 : json 데이터 삽입 데이터 형과 찾으려는 데이터 형이 같아야함 (int = 1 표시 / String = "1" 표시)]
          var jsonIdx = jsonArray.findIndex(function(key) {return key["idx"] === 2});
          console.log("");
          console.log("[runFunction] : [KEY=IDX] : " + 2);
          console.log("[runFunction] : [array] : " + JSON.stringify(jsonIdx));
          console.log("[runFunction] : [jsonData] : " + JSON.stringify(jsonArray[jsonIdx]));
          console.log("");
          
       };

    </script>

[결과 출력]


[요약 설명]

/*

[JS 요약 설명]

1. window onload : 웹 브라우저 로딩 완료 상태를 나타냅니다

2. new Array : 배열 형태로 데이터를 저장합니다

3. new Object : 오브젝트 형태로 데이터를 저장합니다 (json 가능)

4. findIndex : 찾으려는 데이터를 포함하고 있는 인덱스 값을 반환합니다 (0부터 시작 / 없으면 -1값)

*/


 

반응형
Comments