0

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

6 Answers 6

1

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'))

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

Comments

0

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

Comments

0

you can do this :

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

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

    console.log(name)

Comments

0

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)

Comments

0

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.

Comments

0

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);

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.