我正在使用Javascript将InDesign文件转换为ANF(Apple News Format,这是JSON)。
在ANF中,每个组件只能有一个段落样式(等效于文本框架)。
在InDesign中,文本框中可以有多个段落样式。解决方法是,可以在容器组件中放置多个组件,以保持布局正确。为此,当我在InDesign文档中找到具有多个段落样式的文本框时,我将创建一个容器组件,然后为每个段落创建一个组件并将其嵌套在容器内。
如果文本框中的两个或多个 CONSECUTIVE 段落具有相同的段落样式,则需要将它们分组为一个嵌套组件。我知道这应该相对简单,但是InDesign中可以使用的Javascript有点过时,因此许多现代便利性不可用。我需要发挥创意。
这是数据的简化示例:
var textContainer = {
role: "container",
components: [
{
textStyle: "style-1",
text: "<p>0</p>",
},
{
textStyle: "style-1",
text: "<p>1</p>",
},
{
textStyle: "style-2",
text: "<p>2</p>",
},
{
textStyle: "style-2",
text: "<p>3</p>",
},
{
textStyle: "style-2",
text: "<p>4</p>",
},
{
textStyle: "style-1",
text: "<p>5</p>",
},
{
textStyle: "style-2",
text: "<p>6</p>",
}
]
}
因此,在数组中有两个位置,其中连续有两组组件相同的textStyle。我需要将它们放在一个组件中。所以我完成后数据应该像这样……
var textContainer = {
role: "container",
components: [
{
textStyle: "style-1",
text: "<p>0</p><p>1</p>",
},
{
textStyle: "style-2",
text: "<p>2</p><p>3</p><p>4</p>",
},
{
textStyle: "style-1",
text: "<p>5</p>",
},
{
textStyle: "style-2",
text: "<p>6</p>",
}
]
}
基本上应该是[[0,1],[2,3,4],5,6]
;
我是这样开始的:
var simplifiedComponents = [];
var consecutive = ""
for(i=0;i<textContainer.components.length;i++){
if(i > 0 && i < textContainer.components.length - 1){
if(textContainer.components[i].textStyle == textContainer.components[i+1].textStyle){
textContainer.components[i].text += textContainer.components[i+1].text;
textContainer.components[i+1].text = "";
}
}
}
但是我被卡住了。
任何人都知道如何将数据转换为此优化版本?
再次,我需要在这里使用基本的Javascript,因为大多数ES5内容对我都不可用。
答案 0 :(得分:0)
var textContainer = {
role: "container",
components: [
{
textStyle: "style-1",
text: "<p>0</p>",
},
{
textStyle: "style-1",
text: "<p>1</p>",
},
{
textStyle: "style-2",
text: "<p>2</p>",
},
{
textStyle: "style-2",
text: "<p>3</p>",
},
{
textStyle: "style-2",
text: "<p>4</p>",
},
{
textStyle: "style-1",
text: "<p>5</p>",
},
{
textStyle: "style-2",
text: "<p>6</p>",
}
]
};
var simplifiedComponents = [];
var consecutive = ""
var components = textContainer.components;
for(var i = 0, l = components.length; i < l; i++){
if (i !== 0 && components[i].textStyle !== components[i - 1].textStyle) {
simplifiedComponents.push({text: consecutive, textStyle:components[i - 1].textStyle});
consecutive = ""
}
consecutive = consecutive += components[i].text;
}
simplifiedComponents.push({text: consecutive, textStyle:components[components.length - 1].textStyle});
console.log(simplifiedComponents);