限制嵌套数组递归JavaScript



假设我有一个数据:

const myArr = [
{   
id: '123',
items: [{   
id: '123',
items: []
},
{   
id: '123',
items: []
},
{   
id: '123',
items: []
}]
},
{   
id: '123',
items: []
},
{   
id: '123',
items: []
}

]

我想递归地切片项目。比方说,如果我只想返回计数2,它应该将第一个"项"过滤为仅2条记录,将嵌套项过滤为2条记录。

到目前为止,我有这个代码,我已经非常困惑

const applyLimitRecursive = (arr) => {
var result
for (let i = 0; i < arr.length; i++) {
if (!arr[i].items) {
result = arr[i]
break
} else {
result = applyLimitRecursive(arr[i].items)
if (result) break
}
}
return result
}

如果数据是可序列化的,则可以使用JSON.parse的复活函数。如果要迭代的值是一个数组,则从中返回一个.slice(0, 2)

const result = JSON.parse(
JSON.stringify(myArr),
(_, val) => Array.isArray(val) ? val.slice(0, 2) : val
);

const myArr = [
{   
id: '123',
items: [
{
id: 234,
items: [
{ id: 5 },
{ id: 6 },
{ id: 7 },
]
},
]
}
];
const result = JSON.parse(
JSON.stringify(myArr),
(_, val) => Array.isArray(val) ? val.slice(0, 2) : val
);
console.log(result);

或者,更手动地进行:

const transform = (item) => {
if (Array.isArray(item)) {
return item.map(transform).slice(0, 2);
}
if (typeof item === 'object' && item !== null) {
return Object.fromEntries(
Object.entries(item).map(
([key, val]) => [key, transform(val)]
)
);
}
// primitives:
return item;
};
const result = transform(myArr);

const myArr = [
{   
id: '123',
items: [
{
id: 234,
items: [
{ id: 5 },
{ id: 6 },
{ id: 7 },
]
},
]
}
];
const transform = (item) => {
if (Array.isArray(item)) {
return item.map(transform).slice(0, 2);
}
if (typeof item === 'object' && item !== null) {
return Object.fromEntries(
Object.entries(item).map(
([key, val]) => [key, transform(val)]
)
);
}
// primitives:
return item;
};
const result = transform(myArr);
console.log(result);

我不确定你在找什么,但我猜就是这个?

function deeper(array, deep){
if(array.length-1 < deep){
return undefined;
}
const q = array[deep];
if(typeof q === 'object' && q.items instanceof Array){
return deeper(q.items, deep);
}
return q;
}
const myArr = [
{ // 0   
id: '123a',
items: [
{   
id: '123',
items: ['zero', 'one', 2]
},
{   
id: '123',
items: []
},
{   
id: '123',
items: ['a']
}]
},
{ // 1 
id: '123',
items: [
{
id: '456',
items : [
{
more: 'stuff',
lame: false,
id: '25',
items: ['c', 'd']
}
]
},
{
id: '456',
items : [
{
items: ['a', 'b']
},
{
more: 'yup',
lame: true,
id: 789,
items: ['see', 'one', 'test']
}
]
}
]
},
{ // 2
id: '123',
items: []
} 
]
console.log(deeper(myArr, 0));
console.log(deeper(myArr, 1));
console.log(deeper(myArr, 2));

注意,deep是基于索引的。