L
L
lue merg2020-07-05 14:17:20
JavaScript
lue merg, 2020-07-05 14:17:20

How to move a child object?

There is an array of objects:

const boxes = [
{
    id: 1,
    inner: [
        {
            id: 2,
            inner: [
                {
                    id: 3,
                    inner: []
                },
                {
                    id: 4,
                    inner: []
                }
            ]
        }, 
        {
            id: 5,
            inner: []
        }
    ]
}]


It is necessary to write an algorithm that will take the box_id object and move it to to_id.

Let the function be putBox, then after executing putBox(3, 1) we get:
const boxes = [
{
    id: 1,
    inner: [
        {
            id: 2,
            inner: [
                {
                    id: 4,
                    inner: []
                }
            ]
        }, 
        {
            id: 5,
            inner: []
        },
        {
            id: 3,
            inner: []
        },
    ]
}]

That is, from the box_id = 2 object, transferred to box_id = 1

The algorithm as I see it
Find the element we want to transfer,
Write this element to a variable,
Delete this element from the array,
Find the element into which our object needs to be inserted,
Push to the inner property previously written variable

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
lue merg, 2020-07-05
@luemerg

Added the delete function and rewrote the search (now the functions are clean)

//GET
const findEl = (ar, id) => {
  return ar.reduce((a, el) => {
    if (a !== null)
      return a
    return el.id === id ? el : findEl(el.inner, id)
  }, null)
}
//REMOVE
const removeEl = (ar) => {
  for (let i = 0; i < ar.length; i++) {
    if (ar[i].inner.length)
      removeEl(ar[i].inner)
    if (ar[i].id === action.box_id)
      delete ar[i]
  }
}

Now if everything is beautifully combined, then everything will work.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question