Home > Software design >  How to access value of data inside nested object in react
How to access value of data inside nested object in react

Time:10-20

I am new to react and having problem trying to access data inside of the nested object. I am trying to create a app where the condition checks todays date with the date of the list and if the condition is true it returns the list.

The list looks like this :


const data = [{
    id: 1,
    name : 'Ashley',
    birthday : {
      year : 1998,
      month: 5,
      date : 22,
    },
    img : 'img'
  },
  {
    id: 2,
    name : 'Bill',
    birthday : {
      year : 1993,
      month: 2,
      date : 12,
    },
    img : 'img'
  },
];

I have made a date object with which the comparision will be done.

const today = new Date();
const year = today.getFullYear();
const month = today.getMonth() 1;
const date = today.getDate();

In the list, the birthday contains three other values and i can not access them using 'filter' method.

The rest of code are below :

function App() {
  const [people, setPeople] = useState(data)
  return (
    <section className = 'container'>
      <h1>{List.length} birthdays today</h1>
    <List people= {people}/>
      <button className="btn" onClick ={() => { setPeople([])}}>Clear All</button>
    </section>
  )
}
const List = ({people}) =>{
  return (
    <>
     { data.filter((person) => {
       const {id, name, birthday, img} = person;
       const age = year-person.birthday.year;
      if(person.birthday.month === month && person.birthday.date === date){
        return(
         <article className= 'person' key = {id}>
            <h2>{name}</h2>
            <p>{age} years old</p>
            <img src = {img} alt = "person"></img>
         </article>
       )}
       return (
         []
       )
     })} 
    </>
  )
}

Sorry about the long description.

CodePudding user response:

The filter function takes a predicate as a parameter that returns true or false, then returns the elements for which the condition is true.

You are returning JSX/an empty array in the predicate, so I am assuming what you want is to actually map the elements to JSX.

Your code would be:

const List = ({people}) =>{
  return (
    <>
      {people.map((person) => {
        const {id, name, birthday, img} = person;
        const age = year - birthday.year;
        if(birthday.month === month && birthday.date === date){
          return (
            <article className='person' key={id}>
                <h2>{name}</h2>
                <p>{age} years old</p>
                <img src={img} alt="person"></img>
            </article>
          )
        }
        return null;
      })} 
    </>
  )
}

I have replaced data by people as it is the correct prop, and [] by null as [] is not valid JSX.

Alternatively, you can filter then map as follow:

const List = ({people}) =>{
  return (
    <>
      {people
        .filter((person) => person.birthday.month === month && person.birthday.date === date)
        .map((person) => {
          const {id, name, birthday, img} = person;
          const age = year - birthday.year;
          return (
            <article className='person' key={id}>
                <h2>{name}</h2>
                <p>{age} years old</p>
                <img src={img} alt="person"></img>
            </article>
          )
        })}
    </>
  )
}

CodePudding user response:

You should be filtering based on the people being passed into List, not the data object.

const List = ({people}) =>{
  return (
    <>
      // instead of data
      { people.filter((person) => {
        const {id, name, birthday, img} = person;
        ...

That will allow you to access id, name, birthday, and img

CodePudding user response:

You dont need filter on single object which is inside array

const data = [{
id: 1,
name : 'Ashley',
birthday : {
  year : 1998,
  month: 5,
  date : 22,
},
img : 'img'
}]

let birthdayYear = data[0].birthday.year
let birthdayMonth = data[0].birthday.month
let birthdayDay = data[0].birthday.date

You can access like this if you have single object only but if multiple then do this

const data = [
{
    id: 1,
    name : 'Ashley',
    birthday : {
      year : 1998,
      month: 5,
      date : 22,
    },
    img : 'img'
    },
{
    id: 2,
    name : 'John',
    birthday : {
      year : 1993,
      month: 4,
      date : 12,
    },
    img : 'img'
    }
]

let myObject = data.find(element=> element.id === 2)
let birthdayYear = myObject.birthday.year
let birthdayMonth = myObject.birthday.month
let birthdayDay = myObject.birthday.date

let me know if you found this complex

CodePudding user response:

You are passing props in curly brackets:

<List people= {people}/>

it should be passed like this:

<List people=people/>

and data.filter should be replaced with people.map.

  • Related