简体   繁体   中英

How to find a value in object of objects with an array of keys

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.

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 ); 

该功能在Ramda中称为path

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM