Я хотел разбить paragraph
на основе этого entityRanges
.
Таким образом, фактический абзац выглядит так:
{
type: 'paragraph',
depth: 1,
text: 'Do you have questions or comments and do you wish to contact ABC? Please visit our customer support page.',
entityRanges: [{
type: 'LINK',
offset: 83,
length: 16,
data: {
target: '_self',
url: '/index.htm'
}
}]
}
Но мои ожидаемые результаты должны быть такими, как показано ниже,
{
type: 'paragraph',
depth: 1,
text: 'Do you have questions or comments and do you wish to contact ABC? Please visit our customer support page.',
entityRanges: [{
type: 'LINK',
offset: 83,
length: 16,
data: {
target: '_self',
url: '/index.htm'
}
}],
embbeded: [{
type: 'text',
text: 'Do you have questions or comments and do you wish to contact ABC? Please visit our '
}, {
type: 'link',
text: 'customer support',
data: {
target: '_self',
url: '/index.htm'
}
}, {
type: 'text',
text: 'page.'
}]
}
Я хотел разбить text
на несколько частей на основе его значений offset
и length
.
В примере customer support
— это значение смещения.
Таким образом, он должен разбиваться в следующем порядке
Все вышеперечисленные части необходимо переместить в новый объект embbeded
.
Надеюсь, я вас правильно понял:
const data = {
"text": "Do you have questions or comments and do you wish to contact ABC? Please visit our customer support page.",
"entityRanges": [{
"type": "LINK",
"offset": 83,
"length": 16,
"data": {
"target": "_self",
"url": "/index.htm"
}
},
{
"type": "LINK",
"offset": 7,
"length": 4,
"data": {
"target": "_self",
"url": "/index.htm"
}
}
]
};
function breakData(data) {
let {
entityRanges,
text
} = data;
const result = [];
let finalPart = '';
let index = 0;
entityRanges
.sort((a, b) => a.offset - b.offset)
.forEach((styleRange) => {
const {
offset,
length,
type,
data
} = styleRange;
const firstPart = text.substring(index, offset);
result.push({
type: 'text',
text: firstPart,
});
index = offset + length; // + 1;
const secondPart = text.substring(offset, index);
result.push({
type,
data,
text: secondPart,
});
finalPart = text.substring(index);
});
if (finalPart) {
result.push({
type: 'text',
text: finalPart,
});
}
data.embbeded = result;
return data;
}
const result = breakData(data);
document.body.innerHTML = '<pre>' + JSON.stringify(result, null, ' ') + '</pre>';