Skip to content
Advertisement

How to work with identical, deeply nested data?

For example, has the following data:

let example = {
  content: [
    ...
    { // index = 3
      id: "b3bbb2a0-3345-47a6-b4f9-51f22b875f22",
      data: {
        value: "hello",
        content: [
          ...
          { // index = 0
            id: "65b1e224-4eae-4a6d-8d00-c1caa9c7ed2a",
            data: {
              value: "world",
              content: [
                ...
                { // index = 1
                  id: "263a4961-efa7-4639-8a57-b20b23a7cc9d",
                  data: {
                    value: "test",
                    content: [
                      // Nesting unknown.
                    ]
                  }
                }
              ]
            }
          }
        ]
      }
    }
  ]
}

And for example an array with indexes leading to the required element(but can be any other):

const ids = [3, 0, 1]

How can you work with an element having this data?

For example, need to change “value” in the element at the specified path in “ids”.

Advertisement

Answer

You could take an array of indices and get the item of the property content by calling the function again for each missing index.

const 
    getElement = ({ content }, [index, ...indices]) => indices.length
        ? getElement(content[index], indices)
        : content[index];

If needed, you could add a guard for a missing index and exit early.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement