자바스크립트 객체가 여러개일 때 배열(?)로 만들 수 있나요?
본문
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(),
};
console.log(depth_1_inp);
});
input에 입력을 받아서
foreach로 돌리면 아래와 같이 데이터가 나옵니다.
위 데이터의 idx는 이전 코드내용입니다.
질문은
그냥 반목문으로 3번 출력 된거 같은데
객체를 1줄씩 배열(?) 에 저장하는 방법은 없을까요?
맞는지는 모르겠지만 적어보자면,
데이터 0 {name: 헬스, price : '100000'}
데이터 1 {name: 요가, price : '200000'}
데이터 2 {name: 점핑, price : '300000'}
이렇게 해서
데이터 겟수만큼 반목해서
객체를 ajax로 보내서 db에 저장 하려고 합니다.
!-->
답변 2
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
function btn_test() {
var arr = [];
$(".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>
<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>
자바스크립트에서 배열은 []을 사용하시면 됩니다.
배열에 요소를 추가하는 방법은 배열.push(object) 메소드를 사용해주시면 됩니다.
베르만님 답변처럼
var array = []; 로 배열 선언 후
반복문 안에서 object를 array.push(object)로 넣어주신 후
array를 찍어보시면 배열로 들어간것을 확인할 수 있습니다.
답변을 작성하시기 전에 로그인 해주세요.