-1

for example I have an object that that has objects and arrays in itself:

const object = 
{
    a: {
        b: [
            0: 'something',
            1: {
                c: 'the thing that I need',
            },
        ],
    },
};

and an array that has the keys as values:

const array =
[
   'a', 'b', '1', 'c',
];

How can I use this array to navigate in the object and give me the value? Maybe there is a way to do this with ramda? or just in general to make it look human readable.

3 Answers3

6

You can reduce the array defining the path through the object. You do have an error in the array. The path should be: [ 'a', 'b', '1', 'c' ], because the thing you need is inside the second element of the b array, not the first.

const object = {
  a: {
    b: [
      'something',
      { c: 'the thing that I need' }
    ],
  },
};
const path = [ 'a', 'b', '1', 'c' ];
const result = path.reduce(( source, next ) => source[ next ], object );
console.log( result );
Shilly
  • 8,511
  • 1
  • 18
  • 24
  • One difference between this and the Ramda `path` function is that this one will throw if an intermediate path is missing. Ramda will return `undefined`. And `pathOr` lets you supply the value to choose in this case. Whether or not this is important to you will depend on your application and its data. But it can be a lifesaver. – Scott Sauyet Sep 26 '18 at 23:31
1

Ian Hoffman-Hicks' superb crocks library has a function that does exactly that

import propPathOr from 'crocks/helpers/propPathOr'
const getC = propPathOr(null, ['a', 'b', '0', 'c'])
getC({ a: { b: [{ c: 'gotcha!' }] } }) === 'gotcha!' // true
Benny Powers
  • 5,398
  • 4
  • 32
  • 55
1

This function is called path in Ramda.

Scott Christopher
  • 6,458
  • 23
  • 26