2

I have an array of keys ['a', 'b', 'c', 'd'] and nested object { a: { b: { c: { d: '58' } } } } How can get a value of nested object '58'? I tried something like this, but I've got only value from one 'level'

const a = ['a', 'b', 'c', 'd']
const b = { a: { b: { c: { d: '58' } } } }
const getValue = (a,b) => { return Object.values(b).find(key => a[key] === b[key]) }
Olian04
  • 6,480
  • 2
  • 27
  • 54
Denis
  • 141
  • 1
  • 7

3 Answers3

4

.reduce() method can help.

Call .reduce() on the array and pass object b as the initial value to the .reduce() method. Callback function of the .reduce() method should just return the result of acc[curr].

During the first call, acc will be the object b and curr will be the first element in the array, i.e. 'a'. So the first call to callback function will return b['a'], i.e. { b: { c: { d: '58' } } }.

const a = ['a', 'b', 'c', 'd'];
const b = { a: { b: { c: { d: '58' } } } };

const result = a.reduce((acc, curr) => acc[curr], b);

console.log(result);
Yousaf
  • 27,861
  • 6
  • 44
  • 69
2

This is a naturally recursive operation, so this is a perfect use case for a recursive function:

const getValue = (Target, [k, ...Kr]) => 
  Kr.length > 0 
    ? getValue(Target[k], Kr)
    : Target[k];

const keys = ['a', 'b', 'c', 'd']
const obj = { a: { b: { c: { d: '58' } } } }

console.log(getValue(obj, keys));

But you could also use array reducers:

const getValue = (obj, keys) => 
  keys.reduce((target, key) => target[key] ,obj);

const keys = ['a', 'b', 'c', 'd']
const obj = { a: { b: { c: { d: '58' } } } }

console.log(getValue(obj, keys));

Or just a regular for loop:

const getValue = (obj, keys) => {
  let target = obj;
  for (let k of keys) {
    target = target[k];
  }
  return target;
}

const keys = ['a', 'b', 'c', 'd']
const obj = { a: { b: { c: { d: '58' } } } }

console.log(getValue(obj, keys));
Olian04
  • 6,480
  • 2
  • 27
  • 54
1
b[a[0]][a[1]][a[2]][a[3]]

it will output 58

I'm not sure if your array a fixed size?

if the size is dynamic

Try

function getValue(a, b) {
    let output = b;
    for (let i = 0; i < a.length; ++i) {
        output = output[a[i]];
    }
    return output;
}
TropicsCold
  • 115
  • 6