我有一个包含字符串和对象的数组。字符串充当“标题”,而跟随它们的对象是“内容”。这样安排是出于虚拟化的目的。这是我到目前为止所得到的
const test = [
"string 1",
{ prop1: "string 1 obj first" },
{ prop1: "string 1 obj" },
{ prop1: "string 1 obj" },
{ prop1: "string 1 obj" },
{ prop1: "string 1 obj last" },
"string 2",
{ prop1: "string 2 obj first" },
{ prop1: "string 2 obj" },
{ prop1: "string 2 obj" },
{ prop1: "string 2 obj last" },
"string 3",
{ prop1: "string 3 obj first" },
{ prop1: "string 3 obj" },
{ prop1: "string 3 obj" },
{ prop1: "string 3 obj" },
{ prop1: "string 3 obj" },
{ prop1: "string 3 obj" },
{ prop1: "string 3 obj last" },
]
const result = test.reduce((acc, curr, i, arr) => {
const next = arr[i+1]
// with Title
if (typeof curr === 'string') {
if (typeof next === 'object' && next !== null) {
// get the index for the next title from here
const nextTitleIndex = test.slice(i + 1).findIndex((item) => typeof item === 'string');
// slice the array from this point up to the index of the next title (not included)
const objects = test.slice(i + 1, nextTitleIndex === -1 ? undefined : nextTitleIndex + 1)
console.log({ nextTitleIndex, objects })
}
}
return acc
}, [])
我需要获取当前迭代的标题和沿线的下一个标题之间的所有对象。 (示例中为“字符串1”和“字符串2”之间的对象等)
第一次和最后一次迭代按预期工作,
objects
变量包含从first
到last
的五/七个对象。然而,中间的迭代不会产生 objects
所需的值,它变成一个空数组。
您没有指定最终结果应该是什么,所以我为您挑选两个:
数组的数组,数组的第一个元素是标题:
const result = [];
test.forEach((s) => {
if(typeof s === 'string') {
result.push([]);
}
result[result.length - 1].push(s); // access error when the test data is not structured correctly
});
console.log(result); // [['string 1', { prop1: "string 1 obj first" }, ...],['string 2', ...], ...]
一个对象,其键是标题,值是内容对象的数组:
const result = {};
let key = undefined;
test.forEach((s) => {
if(typeof s === 'string') {
key = s;
result[key] = [];
} else {
result[key].push(s); // semantic error when the test data is not structured correctly
}
});
console.log(result); // {string 1: [{ prop1: "string 1 obj first" }, ...], string 2: [...], ...}