Nandlal Shah
Nandlal Shah

Reputation: 1

How to get data inside a Nested Array of object

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

Upvotes: 0

Views: 63

Answers (6)

Ahmad Mehmood
Ahmad Mehmood

Reputation: 1

you can do it like this

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

datafromback.map((items) => {
  items.map((item) => {
    if (item?.name) names.push(item?.name);
  });
});
console.log(names);

Upvotes: 0

Fauzan DP
Fauzan DP

Reputation: 51

You can use 0 index

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

const dataFrom = (arr, nameRavi) => {
    let result
    arr.forEach((ele) => {
        if (ele[0].name === nameRavi) result = ele[0].name
    })
    return result
}

console.log(dataFrom(datafromback, 'ravi'))

Upvotes: 1

Amit Bhattacharjee
Amit Bhattacharjee

Reputation: 41

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.

Upvotes: 0

Lucasbk38
Lucasbk38

Reputation: 525

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)

Upvotes: 0

Ali Sattarzadeh
Ali Sattarzadeh

Reputation: 3587

you can do this :

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

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

    console.log(name)

Upvotes: 0

N_A_P
N_A_P

Reputation: 39

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) // 
})

Upvotes: 0

Related Questions