const deepGet = (obj, keys) =>
keys.reduce(
(xs, x) => (xs && xs[x] !== null && xs[x] !== undefined ? xs[x] : null),
obj
);
const dig = (obj, target) =>
target in obj
? obj[target]
: Object.values(obj).reduce((acc, val) => {
if (acc !== undefined) return acc;
if (typeof val === 'object') return dig(val, target);
}, undefined);
let index = 2;
const data = {
foo: {
foz: [1, 2, 3],
bar: {
baz: ['a', 'b', 'c']
}
}
};
deepGet(data, ['foo', 'foz', index]); // get 3
deepGet(data, ['foo', 'bar', 'baz', 8, 'foz']); // null
const data = {
level1: {
level2: {
level3: 'some data'
}
}
};
dig(data, 'level3'); // 'some data'
dig(data, 'level4'); // undefined
Массивы и объекты JavaScript
JavaScript