Home > other >  How to get data inside a Nested Array of object
How to get data inside a Nested Array of object

Time:11-13

const datafromback=[[{name:ravi}],[{}],[{}],[{}]]

I want to access ravi. Can anyone help me how can i see ravi in my console.with dealing with nested arrays

I not getting approach but i can use map to map through datafromback array but don't know how to get inside it

CodePudding user response:

one possible way is to use flat first to remove nested array

const datafromback=[[{name:ravi}],[{}],[{}],[{}]]
const flatternArray = datafromback.flat() // [{name:ravi},{},{},{}]
flatternArray.map(item => {
    console.log(item.name) // 
})

CodePudding user response:

you can do this :

const datafromback=[[{name:'ravi'}],[{}],[{}],[{}]]

const [{name}] =  datafromback.find(data=>data.find(item=>item.name === 'ravi')?.name === 'ravi')

    console.log(name)

CodePudding user response:

You can create a recursive function if you have non-fixed dimensions array :

const handle = e => {
  if (Array.isArray(e))
    return e.map(handle)
  else {
    console.log(e.name)
  }
}

handle(array)

Or if you know the dimensions, you can use nested for loops like so :

// example for 2 dimensions
for (let y = 0; y < array.length; y  )
  for (let x = 0; x < array[y].length; x  )
    console.log(array[y][x].name)

CodePudding user response:

Hey so what you have above is a 2D object array. if you just want to console you can use a nested forEach to get the key value, like this.

datafromback.forEach(data => {
  //this is the nested array that contains the objects
  data.forEach(obj => {
    //here you can access the actual object
    if (obj?.name) console.log(obj.name);
  });
});

this will return the value of key (name) if present ie ravi in your case.

  • Related