我正在尝试用angular8制作问卷。
有一个带有加号按钮的动态表格。您可以通过单击加号按钮添加新字段,该字段应添加到所选字段的下方。为此,我试图使嵌套的json对象,我想在特定对象之后再添加一个对象。
例如-我需要在id为3的对象之后添加新对象
这是我到目前为止所做的
mainConatiners = [
{
page_title : "This is first page.",
"data":[
{
id:1,
title:"This is first question",
type:1,
page:0,
position:'0',
parent:'0'
},
{
id:2,
title:"This is second question",
type:2,
page:0,
position:'1',
parent:0,
"data":[
{
key:"[data][1][data][0]",
id:3,
title:"This is third question",
type:1,
page:0,
position:'1-0',
parent:2
},
{
id:4,
title:"This is fourth question",
type:2,
page:0,
position:'1-1',
parent:2,
"data":[
{
id:5,
title:"This is tenth question",
type:2,
page:0,
position:'1-1-0',
parent:'2-4'
}
]
}
]
}
]
}]
预期产量-
mainConatiners = [
{
page_title : "This is first page.",
"data":[
{
id:1,
title:"This is first question",
type:1,
page:0,
position:'0',
parent:'0'
},
{
id:2,
title:"This is second question",
type:2,
page:0,
position:'1',
parent:0,
"data":[
{
key:"[data][1][data][0]",
id:3,
title:"This is third question",
type:1,
page:0,
position:'1-0',
parent:2
},
{
key:"[data][1][data][0]",
id:12,
title:"This is third question",
type:1,
page:0,
position:'1-0',
parent:2
},
{
id:4,
title:"This is fourth question",
type:2,
page:0,
position:'1-1',
parent:2,
"data":[
{
id:5,
title:"This is tenth question",
type:2,
page:0,
position:'1-1-0',
parent:'2-4'
}
]
}
]
}
]
}]
这是一个可变的解决方案-我们首先将所有对象索引到idHash映射,该映射包含有关对象ID,数据数组中的对象索引和dara数组本身(parentArr)的信息-然后找到10个对象id = 3并在其后声明new。
let idHash = {} // id=> hash object (hash obiect= {obj,index,parentArr)}
let makeHash = data => (data||[]).forEach((d,i)=>
(idHash[d.id]={ obj:d, index:i, parentArr: data}, makeHash(d.data)));
makeHash(mainConatiners);
let hobj = idHash[3] // hash object with object id=3 after which we want to insert
hobj.parentArr.splice(hobj.index+1,0,newObj);
mainConatiners = [{
page_title: "This is first page.",
"data": [{
id: 1,
title: "This is first question",
type: 1,
page: 0,
position: '0',
parent: '0'
},
{
id: 2,
title: "This is second question",
type: 2,
page: 0,
position: '1',
parent: 0,
"data": [{
key: "[data][1][data][0]",
id: 3,
title: "This is third question",
type: 1,
page: 0,
position: '1-0',
parent: 2
},
{
id: 4,
title: "This is fourth question",
type: 2,
page: 0,
position: '1-1',
parent: 2,
"data": [{
id: 5,
title: "This is tenth question",
type: 2,
page: 0,
position: '1-1-0',
parent: '2-4'
}]
}
]
}
]
}]
let newObj = {
key: "[data][1][data][0]",
id: 12,
title: "This is third question",
type: 1,
page: 0,
position: '1-0',
parent: 2
}
let idHash = {} // id=> hash object (hash obiect= {obj,index,parentArr)}
let makeHash = data => (data||[]).forEach((d,i)=>
(idHash[d.id]={ obj:d, index:i, parentArr: data}, makeHash(d.data)));
makeHash(mainConatiners);
let hobj = idHash[3] // hash object with object id=3 after which we want to insert
hobj.parentArr.splice(hobj.index+1,0,newObj);
console.log(mainConatiners)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句