Home > database >  How to access an object inside another object in javascript
How to access an object inside another object in javascript

Time:10-11

I have a problem to display the properties of an object that is inside another object... I made a relationship in the backend with typeorm using relations to bring the departments into the users, but I can't use them in the user request because the request is arriving as [[prototype]].

import { getUsersDataId } from 'services/usuarios'
import store from 'store'

const General7 = () => {
  const [users, setUsers] = useState({})

  const id = store.get('id')

  const getUsers = async () => {
    const data = await getUsersDataId(id)
    setUsers(data)
  }

  useEffect(() => {
    getUsers()
  }, [])

  console.log(users)


  return (
    <div>
      <div className="d-flex flex-wrap align-items-center mb-2">
        <div className="flex-shrink-0 vb__utils__avatar mr-4 mb-2">
          <img src="resources/images/avatars/5.jpg" alt="Mary Stanform" />
        </div>
        <div className="mb-2">
          <div className="text-dark font-size-18 font-weight-bold text-nowrap">
            {users.name}
            <i className="align-text-bottom fe fe-check-square text-success ml-2 font-size-24 " />
          </div>
          <div className="text-uppercase">Support team</div>
        </div>
      </div>
      <div className="mb-3">
        <a className="btn btn-outline-primary mr-2">Chat</a>
        <a className="btn btn-outline-danger">Unfollow</a>
      </div>
      <div className="table-responsive">
        <table className="table table-borderless">
          <tbody>
            <tr>
              <td className="text-gray-6 pl-0">Departamento</td>
              <td className="pr-0 text-right text-dark">{users.department.name}</td>
            </tr>
            <tr>
              <td className="text-gray-6 pl-0">Ocupação</td>
              <td className="pr-0 text-right text-dark">{users.occupation}</td>
            </tr>
            <tr>
              <td className="text-gray-6 pl-0">Tempo de Experiência</td>
              <td className="pr-0 text-right text-dark">{users.timeExperience}</td>
            </tr>
            <tr>
              <td className="text-gray-6 pl-0">Email</td>
              <td className="pr-0 text-right text-dark">{users.email}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  )
}

export default General7


The getUsers() function returns me the following result

{id: 29, profileId: 1, name: 'Thiago Gouvêa', email: '[email protected]', password: '$2a$08$9yGZGer452gOfSa2h0mUwu92Xq.038fx2pV7nEV3XLPSuuyxBJPnC', …}
active: true
avatar: null
createdAt: "2021-10-09T02:49:22.871Z
"createdBy: null
departmentId: 1
email: "[email protected]
"forgottenPasswordCode: null
forgottenPasswordTime: null
id: 29
lastAccess: null
name: "Thiago Gouvêa"
occupation: "Desenvolvedor front-end"
password: "$2a$08$9yGZGer452gOfSa2h0mUwu92Xq.038fx2pV7nEV3XLPSuuyxBJPnC"
profileId: 1
timeExperience: 2
updatedAt: null
[[Prototype]]: Object

I need to access what's in the prototype that should come as follows

 {
    "id": 29,
    "profileId": 1,
    "name": "Thiago Gouvêa",
    "email": "[email protected]",
    "password": "$2a$08$9yGZGer452gOfSa2h0mUwu92Xq.038fx2pV7nEV3XLPSuuyxBJPnC",
    "occupation": "Desenvolvedor front-end",
    "departmentId": 1,
    "timeExperience": 2,
    "avatar": null,
    "lastAccess": null,
    "active": true,
    "forgottenPasswordCode": null,
    "forgottenPasswordTime": null,
    "createdAt": "2021-10-09T02:49:22.871Z",
    "updatedAt": null,
    "createdBy": null,
    "department": {
      "id": 1,
      "name": "Desenvolvimento",
      "description": "Departamento dos Devs"
    }
  }

I'm trying to return the department values ​​but when I use users.department.name the return is undefined

So is my backend route to query users

usersRouter.get('/', async (request, response) => {   
const usersRepository = getCustomRepository(UsersRepository);   
const users = await usersRepository.find({     
relations: ['department'],
   });    
return response.json(users); 
}); 

CodePudding user response:

Unless your user->department relation is set to be eager, you'll need to load the lazy relation.

eg:

const user = await connection.getRepository(User).findOne(1);
const department = await user.department;
// you'll have all user's department inside "department" variable now

Otherwise you could try making your relation eager like this:

@Entity('users')
class User {
    ...

    @ManyToMany(type => Department, department => department.name, {
        eager: true
    })

    @JoinTable()

    department: Department[];

}

Eager relations are loaded automatically each time you load entities from the database.

See eager and lazy relations

  • Related