NCHAryON
NCHAryON

Reputation: 61

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".

Upvotes: 1

Views: 45

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386654

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.

Upvotes: 2

MauriceNino
MauriceNino

Reputation: 6757

You can just recursively loop over your element and change the value, if you got to the last element.

I have written a small example, all you would have to do, is to extend the method for your own data structure (el.data.content):

const el = [[1,2], [3,4], [5,6]];

const changeEl = (el, indexArr, val) => {
  if(indexArr.length == 1) {
    el[indexArr[0]] = val;
  } else {
    changeEl(el[indexArr.shift()], indexArr, val);  
  }
}

changeEl(el, [1, 0], 99);
console.log(el);

Upvotes: 1

Related Questions