这是数组格式[{"name":"Rose","number":"+919224512555"},{"name":"smith","number":"+91975555224"}]
,是从我的棱角形式中得到的,它有一个动态表,分别带有列名和列号。
我想将上述数组转换为以下格式存储在数据库中。
"name": [
{
"first_name": "Rose",
"formatted_name": "Rose",
},
{
"first_name": "smith",
"formatted_name": "Smith",
},
] ,
"phones": [
{
"phone": "+919224512555",
"type": "HOME"
},
{
"phone": "+91975555224",
"type": "HOME",
}
],
我在前端开发中使用angular,在后端使用laravel
答案 0 :(得分:0)
我认为这可能是更好的方法
const data = [
{ name: "Rose", number: "+919224512555" },
{ name: "smith", number: "+91975555224" },
]
const mapped = {
"name": data.map((item) => ({
first_name: item.name,
formatted_name: item.name, // do your own formatting here
})),
"phone": data.map((item) => ({
phone: item.number,
type: item.number, // do your own processing here
}))
}
console.log(mapped)
希望它对您有益
答案 1 :(得分:0)
您可以使用Array#reducer
const arr = [{"name":"Rose","number":"+919224512555"},{"name":"smith","number":"+91975555224"}];
const res = arr.reduce((a,{name,number})=>{
a.name = a.name||[];
a.name.push({first_name:name,formatted_name:name});
a.phones = a.phones||[];
a.phones.push({phone:number,type:'HOME'});
return a;
},{})
console.log(res)
答案 2 :(得分:-1)
下面的代码应该可以帮助您重组JSON对象
const req_body = [
{ name:"Rose", number:"+919224512555" },
{ name:"smith", number:"+91975555224"}
]
const restrutured_body = {
name: [],
phone: []
};
req_body.forEach((item) => {
restrutured_body.name.push({
first_name: item.name,
formatted_name: item.name
});
restrutured_body.phone.push({
phone: item.number,
type: 'HOME'
});
});
console.log(restrutured_body);