[JavaScript] FormData에 다차원 object append (append multidimensional object to FormData)
JavaScript 2019. 12. 11. 13:57
function setFormData(formData, data, parentKey)
{
if (!(formData instanceof FormData)) return;
if (!(data instanceof Object)) return;
Object.keys(data).forEach(key => {
const val = data[key];
if (parentKey) key = `${parentKey}[${key}]`;
if (val instanceof Object && !Array.isArray(val)) {
return setFormData(formData, val, key);
}
if (Array.isArray(val)) {
val.forEach((v, idx) => {
if (v instanceof Object) {
setFormData(formData, v, `${key}[${idx}]`);
}
else {
formData.append(`${key}[${idx}]`, v);
}
});
}
else {
formData.append(key, val);
}
});
}
위 함수를 이용해 FormData에 다차원 object를 append하고 결과를 출력해보면 아래와 같음.
// 테스트용 다차원 object
const data = {
str_k: 'bloodguy',
int_k: 999,
bool_k: false,
obj_k: {
str_k2: 'nicehide',
int_k2: 222,
bool_k2: true,
obj_k2: {
str_k3: 'str',
int_k3: 333,
bool_k3: false,
arr_k3: [
1, 'arr_str', true
]
},
arr_k2: [
2, 'k2',
{
str_k_in_arr_k2: 'sss',
int_k_in_arr_k2: 136
}
]
},
friends: [
{
name: 'nicehide',
gender: 'unknown'
},
{
name: 'nobody',
gender: 'female'
}
]
};
const formData = new FormData();
setFormData(formData, data);
const arrQueryString = [];
for (let pair of formData.entries()) {
console.log(`${pair[0]} = ${pair[1]}`);
arrQueryString.push(`${pair[0]}=${pair[1]}`);
}
console.log(`query string = ${arrQueryString.join('&')}`);
// 결과 출력
str_k = bloodguy
int_k = 999
bool_k = false
obj_k[str_k2] = nicehide
obj_k[int_k2] = 222
obj_k[bool_k2] = true
obj_k[obj_k2][str_k3] = str
obj_k[obj_k2][int_k3] = 333
obj_k[obj_k2][bool_k3] = false
obj_k[obj_k2][arr_k3][0] = 1
obj_k[obj_k2][arr_k3][1] = arr_str
obj_k[obj_k2][arr_k3][2] = true
obj_k[arr_k2][0] = 2
obj_k[arr_k2][1] = k2
obj_k[arr_k2][2][str_k_in_arr_k2] = sss
obj_k[arr_k2][2][int_k_in_arr_k2] = 136
friends[0][name] = nicehide
friends[0][gender] = unknown
friends[1][name] = nobody
friends[1][gender] = female
query string = str_k=bloodguy&int_k=999&bool_k=false&obj_k[str_k2]=nicehide&obj_k[int_k2]=222&obj_k[bool_k2]=true&obj_k[obj_k2][str_k3]=str&obj_k[obj_k2][int_k3]=333&obj_k[obj_k2][bool_k3]=false&obj_k[obj_k2][arr_k3][0]=1&obj_k[obj_k2][arr_k3][1]=arr_str&obj_k[obj_k2][arr_k3][2]=true&obj_k[arr_k2][0]=2&obj_k[arr_k2][1]=k2&obj_k[arr_k2][2][str_k_in_arr_k2]=sss&obj_k[arr_k2][2][int_k_in_arr_k2]=136&friends[0][name]=nicehide&friends[0][gender]=unknown&friends[1][name]=nobody&friends[1][gender]=female
'JavaScript' 카테고리의 다른 글
[VisualStudioCode] JavaScript 프로젝트에서 ctrl + 클릭으로 import 파일 열기 (0) | 2020.05.12 |
---|---|
[JavaScript] 특정 년월의 마지막 날짜 가져오기 (get last day of month) (0) | 2020.02.12 |
[JavaScript] 숫자를 서수(Ordinal Number)로 변환하기 (convert numbers to ordinal numbers) (1) | 2019.10.11 |
[JavaScript] javascript로 pseudo-element style 변경하기 (0) | 2019.05.31 |
[JavaScript] Date.toISOString() timezone offset 반영 (3) | 2017.04.20 |