Skip to content

Instantly share code, notes, and snippets.

@cs09g
Created May 2, 2016 08:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cs09g/c5c265cfa14309901ce448d8a320a40a to your computer and use it in GitHub Desktop.
Save cs09g/c5c265cfa14309901ce448d8a320a40a to your computer and use it in GitHub Desktop.
일반 폼을 JSON 을 위한 형태로 변형하기
{
a0: {b0: c0},
a1: b1,
a2: {b2: {c1: d0, c2: d1}}
}
이런 형태의 JSON 을 보내야 하고, 입력 form을 다음과 같이 설정하였을 때 사용하기 위한 코드이다.
<input id="a0.b0">
<input id="a1">
<input id="a2.b2.c1">
<input id="a2.b2.c2">
현재 구현은 2중첩 까지만 가능하도록 되어 있고, 최종 목표는 무제한까지 가능하도록 하는 것이다.
for (var param in params) {
if (param.indexOf(".") != -1) {
// 하위 항목이 있는 parameter
// dot 을 기준으로 앞은 상위, 뒤는 하위 parameter이다.
// 상위 parameter가 이미 존재할 경우 하위 parameter가 있는 map 에 새로 추가한다.
// dot 은 최대 둘만 있다고 가정한다.
// parent.child.baby = value
// ==> {parent: {child: {baby: value}}}
// 현재 구현은 dot 이 하나 포함되었을때만 정상
var parent = param.split(".")[0];
var child = param.split(".")[1];
var baby = param.split(".")[2];
if (query[parent] !== undefined) { // 이미 어떤 값이 들어 있을 때
var origin = query[parent];
origin[child] = encodeURI(params[param]);
if (baby !== undefined) {
console.log(origin);
/*
var innerKV = {};
console.log(baby);
innerKV[baby] = encodeURI(params[param]);
origin[child] = innerKV;
*/
}
query[parent] = origin;
}
else { // 처음 값이 들어갈 때
var newKV = {};
newKV[child] = encodeURI(params[param]);
if (baby !== undefined) {
console.log(newKV);
var innerKV = {};
innerKV[baby] = encodeURI(params[param]);
newKV[child] = innerKV;
}
query[parent] = newKV;
}
}
else {
// 단순 parameter
// 처리할 필요 없이 바로 query[param]에 넣어주면 된다.
query[param] = encodeURI(params[param]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment