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

 

 

Posted by bloodguy
,