我正在使用一些wordpress项目这个项目关于通过术语类别搜索游览这个我使用jQuery ui catcomplete由我的数组不支持catcomplete所以我想将我的数组转换为JSON对象 这是我的阵列现在:
1:
1:{label: "Namibia", category: "Afrika"}
2:{label: "Sydafrika", category: "Afrika"}
3:{label: "Tanzania", category: "Afrika",}
4:{label: "Madagaskar", category: "Afrika"}
2:
1:{label: "Colombia", category: "Amerika"}
2:{label: "Kuba", category: "Amerika"}
3:{label: "Private: Peru", category: "Amerika"}
4:{label: "Panama", category: "Amerika"}
5:{label: "Costa Rica", category: "Amerika"}
3:
1:{label: "Private: Södra Indien", category: "Asien"}
2:{label: "Indonesien", category: "Asien"}
3:{label: "Filippinerna", category: "Asien"}
4:{label: "Indien", category: "Asien"}
5:{label: "Kambodja", category: "Asien"}
6:{label: "Vietnam", category: "Asien"}
7:{label: "Myanmar", category: "Asien"}
8:{label: "Sri Lanka", category: "Asien"}
9:{label: "Thailand", category: "Asien"}
我希望它像这样
data:{label: "Namibia", category: "Afrika"},
{label: "Sydafrika", category: "Afrika"},
{label: "Tanzania", category: "Afrika",},
{label: "Madagaskar", category: "Afrika"},
{label: "Colombia", category: "Amerika"},
{label: "Kuba", category: "Amerika"},
{label: "Private: Peru", category: "Amerika"},
{label: "Panama", category: "Amerika"},
{label: "Costa Rica", category: "Amerika"},
{label: "Private: Södra Indien", category: "Asien"},
{label: "Indonesien", category: "Asien"},
{label: "Filippinerna", category: "Asien"},
{label: "Indien", category: "Asien"},
{label: "Kambodja", category: "Asien"},
{label: "Vietnam", category: "Asien"},
{label: "Myanmar", category: "Asien"},
{label: "Sri Lanka", category: "Asien"},
{label: "Thailand", category: "Asien"},
感谢。
答案 0 :(得分:1)
您可以使用map
,reduce
和concat
使用map
将对象转换为2维数组。
使用reduce
循环访问数组并使用concat
let data = {
1: {
1: {
label: "Namibia",
category: "Afrika"
},
2: {
label: "Sydafrika",
category: "Afrika"
},
3: {
label: "Tanzania",
category: "Afrika"
},
4: {
label: "Madagaskar",
category: "Afrika"
},
},
2: {
1: {
label: "Colombia",
category: "Amerika"
},
2: {
label: "Kuba",
category: "Amerika"
},
3: {
label: "Private: Peru",
category: "Amerika"
},
4: {
label: "Panama",
category: "Amerika"
},
5: {
label: "Costa Rica",
category: "Amerika"
},
},
3: {
1: {
label: "Private: Södra Indien",
category: "Asien"
},
2: {
label: "Indonesien",
category: "Asien"
},
3: {
label: "Filippinerna",
category: "Asien"
},
4: {
label: "Indien",
category: "Asien"
},
5: {
label: "Kambodja",
category: "Asien"
},
6: {
label: "Vietnam",
category: "Asien"
},
7: {
label: "Myanmar",
category: "Asien"
},
8: {
label: "Sri Lanka",
category: "Asien"
},
9: {
label: "Thailand",
category: "Asien"
},
}
};
let newData = Object.values(data).map(v => {
let x = [];
for (let k in v) x.push(v[k]);
return x;
}).reduce((c, v) => {
c = c.concat(v);
return c;
}, []);
console.log(newData);
您也可以尝试更短的版本:
let newData = Object.values(data).reduce((c, v) => c.concat(Object.values(v).map(i => i)),[]);