I have an array of objects something like this
arr = [{"class":"section"},{"fieldGroup":[]},{"class":"col","name":"input"},{"class":"col","name":"dropdown"},{"class":"col","name":"date"},{"fieldGroup":[]},{"class":"col","name":"table"}]
Now I need to move the objects with "class":"col"
inside its previous object which contains "fieldGroup"
So my desired output should be like this
arr = [{"class":"section"},{"fieldGroup":[{"class":"col","name":"input"},{"class":"col","name":"dropdown"},{"class":"col","name":"date"}]},{"fieldGroup":[{"class":"col","name":"table"}]}]
I have tried this piece of code
arr.forEach((item: any, index: number) => {
if (item.class === "col") {
arr[index - 1].fieldGroup.push(item);
arr.splice(index, 1);
}else {
return arr;
}
})
but getting an error saying cannot read property push of undefined
any help?