我有一組嵌套物件。我正在嘗試從中洗掉我需要的元素。如果我傳遞了一個未嵌套的元素,那么一切正常。但是,如果我嘗試洗掉嵌套的,它就不起作用。告訴我錯在哪里
import React, { useState, useEffect } from 'react';
let array = [
{
id: 1,
title: 'text 1',
children: [
{
id: 5,
title: 'text 5',
children: [],
},
{
id: 6,
title: 'text 6',
children: [],
},
],
},
{
id: 2,
title: 'text 2',
children: [],
},
{
id: 3,
title: 'text 3',
children: [
{
id: 7,
title: 'text 7',
children: [],
},
],
},
{
id: 4,
title: 'text 4',
children: [],
},
];
export const Component = () => {
const [state, setState] = useState(array);
const onDelete = (arr, id) => {
let result = [...arr].filter((item) => {
if (item.id !== id) {
return item;
} else {
item.children.length && onDelete(item.children, id);
}
});
setState(result);
};
useEffect(() => {
onDelete(state, 5);
}, []);
return <div></div>;
};
我有一組嵌套物件。我正在嘗試從中洗掉我需要的元素。如果我傳遞了一個未嵌套的元素,那么一切正常。但是,如果我嘗試洗掉嵌套的,它就不起作用。告訴我錯在哪里
uj5u.com熱心網友回復:
我們可以使用一個通用的深度過濾函式,它接受一個謂詞函式并在子節點上遞回。這可以讓我們做各種各樣的其他事情:洗掉一個欄位中具有奇數值的所有節點,或者只保留另一個欄位中具有特定值的那些節點。對于我們的例子,我們可以onDelete對該過濾函式進行簡單的包裝。代碼可能如下所示:
const deepFilter = (pred) => (xs) =>
xs .flatMap (({children = [], ...rest}) =>
pred (rest)
? [{... rest, children: deepFilter (pred) (children)}]
: []
)
const onDelete = (arr, id) =>
deepFilter (x => x.id !== id) (arr)
let array = [{id: 1, title: "text 1", children: [{id: 5, title: "text 5", children: []}, {id: 6, title: "text 6", children: []}]}, {id: 2, title: "text 2", children: []}, {id: 3, title: "text 3", children: [{id: 7, title: "text 7", children: []}]}, {id: 4, title: "text 4", children: []}]
console .log ('original: ', array)
console .log ('after removing 3: ', onDelete (array, 3))
console .log ('after removing 5: ', onDelete (array, 5))
.as-console-wrapper {max-height: 100% !important; top: 0}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/531173.html
上一篇:Google表格:ArrayFormulasumifs(帶有IFERROR)。如何添加額外的標準?
下一篇:錯誤列印的排序陣列
