테스트 사이트 - 개발 중인 베타 버전입니다

자바스크립트 객체가 여러개일 때 배열(?)로 만들 수 있나요? 채택완료

세진컴퓨터랜드 2년 전 조회 1,944

3차 카테고리 메뉴를 만들고 있는데

 

일단 1단계에서

추가 버튼을 누르면 1단계 입력 창은 계속 생기고

 

스크립트에서

 $(".input-options-wrapper [data-depth='0']").each(function () {

                var $depth0 = $(this).children(".option-form");

                

                var depth_1_inp = {                    

                    name: $depth0.find(".input-name").val(),

                    price: $depth0.find(".input-price").val(),

                };</p>

<p>               

                console.log(depth_1_inp);

             </p>

<p>            });

input에 입력을 받아서

foreach로 돌리면 아래와 같이 데이터가 나옵니다.

 

위 데이터의 idx는 이전 코드내용입니다.

 

질문은 

 

그냥 반목문으로 3번 출력 된거 같은데

객체를 1줄씩 배열(?) 에 저장하는 방법은 없을까요?

 

맞는지는 모르겠지만 적어보자면, 

데이터 0 {name: 헬스, price : '100000'}

데이터 1 {name: 요가, price : '200000'}

데이터 2 {name: 점핑, price : '300000'}

 

이렇게 해서

데이터 겟수만큼 반목해서

객체를 ajax로 보내서 db에 저장 하려고 합니다.

 

 

댓글을 작성하려면 로그인이 필요합니다.

답변 2개

채택된 답변
+20 포인트
2년 전

</p>

<p><script src="<a href="http://code.jquery.com/jquery-latest.min.js"></script>" target="_blank" rel="noopener noreferrer">http://code.jquery.com/jquery-latest.min.js"></script></a>

<script>

function btn_test() {

    var arr = [];</p>

<p>    $(".input-options-wrapper [data-depth='0']").each(function () {

        var $depth0 = $(this).children(".option-form");

        

        var depth_1_inp = {

            name: $depth0.find(".input-name").val(),

            price: $depth0.find(".input-price").val(),

        };

       

        // console.log(depth_1_inp);

        arr.push(depth_1_inp);

    });

    console.log(arr);

}

</script></p>

<p><div class="input-options-wrapper">

    <ul data-depth="0">

        <li class="option-form">

            <input type="text" class="input-name" value="헬스" />

            <input type="text" class="input-price" value="100000" />

        </li>

    </ul>

    <ul data-depth="0">

        <li class="option-form">

            <input type="text" class="input-name" value="요가" />

            <input type="text" class="input-price" value="200000" />

        </li>

    </ul>

    <ul data-depth="0">

        <li class="option-form">

            <input type="text" class="input-name" value="점핑" />

            <input type="text" class="input-price" value="300000" />

        </li>

    </ul>

    <ul>

        <li><button type="button" onclick="btn_test()">console print</button></li>

    </ul>

</div></p>

<p>

로그인 후 평가할 수 있습니다

댓글을 작성하려면 로그인이 필요합니다.

자바스크립트에서 배열은 []을 사용하시면 됩니다.

배열에 요소를 추가하는 방법은 배열.push(object) 메소드를 사용해주시면 됩니다.

베르만님 답변처럼

var array = []; 로 배열 선언 후

반복문 안에서 object를 array.push(object)로 넣어주신 후 

array를 찍어보시면 배열로 들어간것을 확인할 수 있습니다. 

로그인 후 평가할 수 있습니다

댓글을 작성하려면 로그인이 필요합니다.

답변을 작성하려면 로그인이 필요합니다.

로그인