1

I have a rootArray with some nested arrays, it could be any depth.

I want to dynamically access a certain inner array, defined by a list of indexes, to push new content there. so for example, if the list of index is

currentFocusedArray = [1,2]

i want to...

rootArray[1][2].push('new content')

dynamically, not hardwired.

Maybe this is a case of the trees not letting me see the forest or maybe I am on a dead end.

I am just making a note taking simple app, with react, very simple yet.

https://codesandbox.io/embed/quirky-gauss-09i1h

Any advice is welcome! Hopefully I didnt waste your time. Thanks in advance.

3
  • You can simply put variables instead of 1 and 2 which you can fill dynamically. Not sure if that's what you mean. Commented Jun 3, 2019 at 12:10
  • I think, you are looking for a recursive function to populate and find any value in nested array. Commented Jun 3, 2019 at 12:14
  • I failed with the title. I need to recursively access an inner array. The depth of the array is not fixed. Commented Jun 3, 2019 at 12:30

3 Answers 3

1

You can write find array to get array based on your focus array. Use array method reduce to find node from an array of indexes

var updateNode = focus.reduce((node,index) => node && node[index], notes);
updateNode && updateNode.push("new content");
Sign up to request clarification or add additional context in comments.

Comments

0

You can make it with a for loop.

let myArray = rootArray
for(let i = 0; i < currentFocusedArray.length; i++){
    myArray = myArray[currentFocusedArray[i]]
}

After this, you will have myArray reference the deep nested value of rootArray.

let rootArray = {
    "1": {
        "2": []
    }
}
 
let currentFocusedArray = [1, 2]
 
let myArray = rootArray
for(let i = 0; i < currentFocusedArray.length; i++){
    myArray = myArray[currentFocusedArray[i]]
}

myArray.push("new content")

console.log(myArray)

Comments

0

You could use reduce to create such function that will set nested array element on any level.

const rootArray = []

function set(arr, index, value) {
  index.reduce((r, e, i, a) => {
    if (!r[e]) {
      if (a[i + 1]) r[e] = []
    } else if (!Array.isArray(r[e])) {
      if (a[i + 1]) {
        r[e] = [r[e]]
      }
    }

    if (!a[i + 1]) {
      if (Array.isArray(r)) {
        r[e] = value
      }
    }

    return r[e]
  }, arr)
}

set(rootArray, [1, 2], 'foo');
set(rootArray, [1, 1, 2], 'bar');
set(rootArray, [1, 2, 2], 'baz');


console.log(JSON.stringify(rootArray))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.