Is there a Javascript library offering a declarative syntax for accessing nested keys through arrays?

Viewed 32

I can use lodash to access nested keys inside Javascript objects:

type Cat = {
  name:  string
  human: Human
}

type Human = {
  name: string
}

const sophie: Cat = {name: 'Sophie', human: {name: 'Courtney'}}

>> console.log(_.get(sophie, 'human.name'))
Courtney

What if I the nested property I want is inside an array?

import {magicNestedGet} from 'unicorn'

type Cat = {
  name:   string
  humans: Human[]
}

const sophie: Cat = {name: 'Sophie', humans: [{name: 'Courtney'}, {name: 'Lukas'}]}

>> console.log(magicNestedGet(sophie, 'humans[].name')) // or maybe 'humans.name[]' ???
[Courtney, Lukas]

I thought lodash did this but I can't get it to work. Is there a library that supports a syntax like this?

1 Answers
  • Here's a solution function (credit to me):
function getPath(object: any, path: string): any {
    if (path[0] == "[") {
        path = path.substr(1);
        var index: int = 0;
        while (/\d/.test(path[0])) {
            index *= 10;
            index += parseInt(path[0]);
            path = path.substr(1);
        }
        path = path.substr(1);
        return getPath(object[index], path);
    }
    var pathNow: string = "";
    while (!".[".includes(path[0])) {
        pathNow += path[0];
        path = path.substr(1);
    }
    return getPath(object[pathNow], path);
}
  • Or, unsafe but more features, use eval:
function getPathWithEval(object: any, path: string): any {
    var r: any;
    eval("r = object." + path);
    return r;
}
  • Or, try, as @connexo says, use <path>[<index>]<path>
Related