1

I'm sure this is a dumb question but I'm really struggling with the syntax for this. In javascript I have this:

  const arr = [
[
  {
    test: "hey1",
  },
  
],
[
  {
    test: "hey2",
  },
  
],

]

This prints out like this:

 Array(2)
0: [{…}]
1: [{…}]

So accessing it right now is like this arr[0][1].test where i just want to be able to access the other arrays in the array like arr[1].test

Hope that makes sense and once again sorry for the dumb question!

1
  • 2
    You're looking for the flat method. Commented Mar 15, 2022 at 11:05

4 Answers 4

2

If I understood your question correctly, you just want to remove one level of nested array. Easiest way would be to just enter the array level into a new array.

var newArray = arr[0];

You can also refer to this. Remove one level of nested arrays from JS data structure

Sign up to request clarification or add additional context in comments.

2 Comments

You can also refer to this , it's just a link that goes to this page again tho
thanks for correcting that, I have pasted the wrong link. here's the reference link: stackoverflow.com/questions/15678355/…. also updated the post.
1

If I understood you correctly you want to unite all the arrays you have into one array

open a new array variable

allArr=[]

And run in a loop on the old array by using Spread Operato

for (let i = 0; i < oldArr.length; i++) {
    allArr.push([...i])

    //OR
    
    allArr= [...allArr,...i]
    
}


1 Comment

Since the question is declaring an arr variable, so we don't need to run this looping logic and merge those. We can simply change the declaration.
1

As Emiel Zuurbier mentioned in the comments - you can simply use flat method:

const arr = [
[
  {
    test: "hey1",
  },
  
],
[
  {
    test: "hey2",
  },
  
],
].flat();

And now this will be your new arr:

enter image description here

Now you can access your element like this:

console.log(arr[0].test)

Comments

0

Just delete the internal square brackets just like this

[
  {Test: 1},
  {Test: 2}
]

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.