I need to mirror the structure of page items in an InDesign document in a javascript object. I need it to match the nesting of page items in groups, groups within groups, etc.
This needs to be extensive to work with any InDesign document that is being worked on.
I need a recursive function that will build my object adding the child frames of any groups it finds and groups within those child frames, etc.
calling the same function if I find a group.
I've tried functions that call themselves if they come across a group, but I get a stack error on large files, on smaller files I only get results that go two levels deep.
var doc = app.activeDocument;
var page = doc.pages[0];
var article = {
id: page.id,
frames: new Array()
}
for(i=0;i<page.pageItems.length;i++){
var po = page.pageItems[i];
var frame_objs = new Array();
var frame_obj = {id: page.pageItems[i].id};
if(po.getElements()[0].constructor.name == "Group"){
frame_obj.frames = getChildFrames(po.pageItems);
}
article.frames.push(frame_obj);
}
create_file("~/Desktop/", "article.json", article);
function getChildFrames(pi_children){
var child_frame_objs = new Array();
for(i=0;i<pi_children.length;i++){
var child_obj = {id: pi_children[i].id};
if(pi_children[i].constructor.name == "Group"){
child_obj.frames = getChildFrames(pi_children[i].pageItems);
}
child_frame_objs.push(child_obj);
}
return child_frame_objs;
}
The idea is to create a object something like this:
{
id: 1,
components: [
{
type: "TextFrame",
id: 201,
}
{
type: "Group",
id: 203,
childFrames: [
{
type: "Rectangle",
id: 1102
},
{
type: "Group",
id: 2034,
childFrames: [
{
type: "TextFrame",
id: 2345
},
{
type: "Group",
id: 99983,
childFrames: [
etc...
]
}
]
}
]
}
]
}
I expect to get a properly simplified version of the page frames structure. As deeply nested as the layout is.
Can someone help me understand how to do this?