在以下JSON结构中,
[
{
"type": "heading-1",
"text": "A title",
},
{
"type": "ordered-list-item",
"text": "Ordered Item A",
},
{
"type": "unordered-list-item",
"text": "Ordered Item B",
},
{
"type": "heading-2",
"text": "A title",
},
{
"type": "ordered-list-item",
"text": "Ordered Item A",
},
{
"type": "unordered-list-item",
"text": "Ordered Item B",
}
];我需要移动所有的类型,作为ordered-list-item和unordered-list-item到新的对象。类似于下面的内容,
{
"type": 'list',
"items": [
{
"type": "ordered-list-item",
"text": "Ordered Item A",
},
{
"type": "unordered-list-item",
"text": "Ordered Item B",
}
]
}最重要的是,我需要维护秩序
例如,应该在新对象内部推送ordered-list-item & unordered-list-item,直到type匹配为止。
因此,使用上面的Json结构,下面是预期的输出
[
{
"type": "heading-1",
"text": "A title",
},
{
"type": "heading-2",
"text": "A title",
},
{
"type": 'list',
"items": [
{
"type": "ordered-list-item",
"text": "Ordered Item A",
},
{
"type": "unordered-list-item",
"text": "Ordered Item B",
}
]
},
{
"type": "heading-1",
"text": "A title",
},
{
"type": 'list',
"items": [
{
"type": "ordered-list-item",
"text": "Ordered Item A",
},
{
"type": "unordered-list-item",
"text": "Ordered Item B",
}
]
},
]如何做到这一点?
发布于 2019-04-29 20:46:46
function deconstruct(data) {
let index = -1;
const out = [];
data.forEach(entry => {
if (entry.type !== 'ordered-list-item' && entry.type !== 'unordered-list-item') {
// If the current entry's type prop is no (un)ordered-list-item
// We push it to the array and reset the index variable to -1
out.push(entry);
index = -1;
} else {
// Else, we check if index is -1. If it is, we push a new object
// And save its index to the index variable
if (index === -1) {
index = out.push({ type: 'list', items: [] }) - 1;
}
// Add the entry to the items of the current list
out[index].items.push(entry);
}
});
return out;
}这是另一种方法:
data.map((entry, index) => {
return {...entry, index, use: entry.type !== 'unordered-list-item' && entry.type !== 'ordered-list-item'}
}).filter(entry => entry.use).map((entry, index, entries) => {
const end = index < entries.length -1 ? entries[index + 1].index : data.length - entry.index;
return [{type: entry.type, text: entry.text}, {type: 'list', items: data.slice(entry.index + 1, entry.index + end)}]
}).flat(2);发布于 2019-04-29 20:41:52
您可以在任何数组上使用array.filter来创建符合条件的新数组(按相同顺序)
const orderedList = yourArray.filter(a => a.type === 'ordered-list-item');
const unOrderedList = yourArray.filter(a => a.type === 'unordered-list-item');然后,只需使用新的过滤数组构建新的json对象。
https://stackoverflow.com/questions/55903469
复制相似问题