我想要的效果

{
    0[1]: "1",
    0[2]: "1",
    0[3]: "1",
    1[1]: "2",
    1[2]: "2",
    1[3]: "2"
}

需要处理的数据

console.log(
    this.toFormData(
        memberList:[
            {
                name:1,
                job:1,
                tel:1
            },
            {
                name:2,
                job:2,
                tel:2
            }
        ],
        // 数据字典
        {
            name: 1,
            job: 2,
            tel: 3
        }
    ),
)

数据处理

toFormData(obj, map = {}) {
    let data = {}
    fn(obj)
    return data
    function fn(obj, name) {
        for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
        let val = obj[key]
        let newName = name ? name + '[' + (map[key] || key) + ']' : key
        if (val instanceof Array || val instanceof Object) {
                     fn(val, newName)
                 } else {
                    if (val === undefined) continue // 跳过 undefined
                    data[newName] = encodeURIComponent(val)
                }
            }
        }
    }
}
文章目录