I
I
Ivan Ivanovich2021-06-16 16:14:58
JavaScript
Ivan Ivanovich, 2021-06-16 16:14:58

How to access the nested properties of an object?

Good day.

There is an object: (for example)

const obj = {
  _id: 1,
  name: 'Tom',
  workers: {
    worderId: 2,
    workerName: 'John',
    someone: {
      surname: 'Tom 2',
    },
  },
};


The matter is that I need to address to nested property through a variable.

I can do it like this:
const v = ['name'];

obj[v]


But the problem is that I still haven't figured out how to access nested objects.

obj['workers']['workerName'] // Ok

const v = ['workers.workerName'];
obj[v] // undefined

const v = 'workers.workerName';
obj[v] // undefined


Tried many different variations but never found a solution.

Please tell me how to solve this problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Cheryabushkin, 2021-06-16
@IwanQ

A bit of perversion)

const v = 'workers.workerName';
const a = v.split('.').reduce((acc, el) => acc = acc[el], obj);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question