Javascript 索引属性的字符串

Javascript 索引属性的字符串,javascript,arrays,Javascript,Arrays,在几个固定选项旁边,我有一个可变数量的是/否无线电输入,名为other[index]。使用$(form).serializeArray()我得到一个名称/值对象数组。使用reduce,我可以将em减少到一个实际对象 const seializedForm = $(event.currentTarget.form).serializeArray(); const gdpr = seializedForm.reduce((aggragation, option) => { retu

在几个固定选项旁边,我有一个可变数量的是/否无线电输入,名为
other[index]
。使用
$(form).serializeArray()
我得到一个名称/值对象数组。使用reduce,我可以将em减少到一个实际对象

const seializedForm = $(event.currentTarget.form).serializeArray();

const gdpr = seializedForm.reduce((aggragation, option) => { 
    return {
        ...aggragation,
        [option.name]: option.value === 'true'
}}, {});
这里的问题是,结果并不是我所需要的:

{
  "canNotify":true,
  "canContact":true,
  "canProcess":true,
  "other[0]":false,
  "other[1]":true,
  "other[2]":false
}
我希望它是:

{
  "canNotify":true,
  "canContact":true,
  "canProcess":true,
  "other": [
      false,
      true,
      false
  ]
}

有什么建议吗?

在不知道完整对象结构的情况下,如果名称包含数组语法,为什么不在返回之前检查名称包含的内容呢
[]
或字符串
other
,那么我们可以假设它是other表单集合结构的一部分

const seializedForm = $(event.currentTarget.form).serializeArray();

const gdpr = seializedForm.reduce((aggragation, option) => {
    if (isInArrayOfOptions(option)) {
        return {
            ...aggragation,
            /* Return a new array combining the current with the next option.value*/
            'other': [...aggragation.other, ...[option.value === 'true']]
        }
    }
    return {
        ...aggragation,
        [option.name]: option.value === 'true'
    }
}, {});

对于每个名称-删除括号,如果该键已存在于数组中,则使用数组排列将值组合到一个数组中:

const serializedForm=[{“name”:“canNotify”,“value”:“true”},{“name”:“canContact”,“value”:“true”},{“name”:“canProcess”,“value”:“false”},{“name”:“other[0]”,“value”:“false”},{“name”:“other[1]”,“value”:“true”},{“name”:“other[2]”,“value”:“false”};
const gdpr=serializedForm.reduce((加总,{name,value})=>{
const isArray=name.includes(“[”);
const key=name.replace(/\[.+\]/g',);
const val=value=='true';
返回{
…加重,
[钥匙]:isArray?[…加积[钥匙]| |[],val]:val
};
}, {});

console.log(gdpr);
你能添加表单吗?@customcommander-是的。它应该始终是一个数组,即使它有一个项目。已修复。我希望找到一种不处理字符串的方法,但这就成功了,这是最完整的答案。谢谢!