Answer the question
In order to leave comments, you need to log in
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',
},
},
};
const v = ['name'];
obj[v]
obj['workers']['workerName'] // Ok
const v = ['workers.workerName'];
obj[v] // undefined
const v = 'workers.workerName';
obj[v] // undefined
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question