DEV Community

aliplutus
aliplutus

Posted on

how to restore recursive array (array with childreN)

if I want to resort data. for example, I want to move the element { id: 0, text: "test one" }, to be a sub inside "main". How to do that?

const myData = [
  { id: 0, text: "test one" },
  { id: 1, text: "test tow" },
  { id: 2, text: "test three" },
  {
    id: 3,
    text: "main",
    sub: [
      { id: 4, text: "sub 1" },
      { id: 5, text: "sub 2" },
    ],
  },
];
Enter fullscreen mode Exit fullscreen mode

I tried to do it by deleting the element and then reinsert it wherever the user drop. but when I uncomment state.push(i.item) or state.splice(f + p, 0, i.item); I got error :Maximum call stack size exceeded event when state = state.filter((el) => el.id !== i.item.id); is uncomented as well.

--

Morover, state = [] dons not work as it expected when element == itembeleong to an item inside the main, I which it should convert main to []

and their are more unexpected issues.

function recursiveUpdate(state, action) {
  // state.splice(i, 1);
  //
  const { item, type, i, f, p } = action;
  state.forEach((element) => {
    if (element == item) {
      console.log({ f: state });
      // state.splice(f + p, 0, i.item);
      // state.push(i.item);
      //state = [];
    }
    if (element.id === i.item.id) {
      console.log({ i: state });
      // state = state.filter((el) => el.id !== i.item.id);
    }
    if (element !== i.item && element !== item && element.sub)
      recursiveUpdate(element.sub, action);
  });

  return state;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)