Skip to content Skip to sidebar Skip to footer

Dynamic Access To An Array In Javascript

Maybe there is already a solution, but I can't find it. I try to access different slots in a multi dimensional array dynamical but with the challenge of different depths. Basically

Solution 1:

If you are sure that all the values in the array will exist, then you can simply use Array.prototype.reduce, like this

console.log(path1.reduce(function(result, currentKey) {
    return result[currentKey];
}, source));
# ping

You can make it generic, like this

functiongetValueFromObject(object, path) {
    return path.reduce(function(result, currentKey) {
        return result[currentKey];
    }, object);
}

And then invoke it like this

console.assert(getValueFromObject(source, path1) === "ping");
console.assert(getValueFromObject(source, path2) === "pong");

Note: You need to make sure that the source is a JavaScript object. What you have now is called an array.

var source = {};   # Note `{}`, not `[]`

Solution 2:

You can loop and build up the value of source before logging it. Try this out:

var sourceValue = source[path[0]];
for (var i = 1; i < path.length; i++) {
    sourceValue = sourceValue[path[i]];
}
console.log(sourceValue);

Here's a JSFiddle that demonstrates this approach works.

Solution 3:

You can get a value from a path (tested code):

var getValue = function(path, context) {
    if ('object' !== typeof context) {
        thrownewError('The context must be an object; "' + typeof context + '" given instead.');
    }
    if ('string' !== typeof path) {
        thrownewError('The path must be a string; "' + typeof context + '" given instead.');
    }

    var fields = path.split('.'),
        getValueFromFields = function(fields, context) {
            var field = fields.shift();

            if (0 === fields.length) {
                return context[field];
            }

            if ('object' !== typeof context[field]) {
                thrownewError('The path "' + path + '" has no value.');
            }

            returngetValueFromFields(fields, context[field]);
        }
    ;

    returngetValueFromFields(fields, context);
}

var source = [];
source['lvl1'] = [];
source['lvl1']['lvl2a'] = [];
source['lvl1']['lvl2a']['lvl3'] = "ping";
source['lvl1']['lvl2b'] = "pong";

console.log(getValue('lvl1.lvl2a.lvl3', source)); // pingconsole.log(getValue('lvl1.lvl2b', source));      // pong

Solution 4:

This question has been answered quite some time ago, but I'd like to show a really simple one line solution using the array reducer:

constgetRoute = (o, r) => r.split(".").reduce((c, s) => c[s], o);

let q = {a:{b:{c:{d:"hello world"}}}};

console.log(getRoute(q, 'a.b.c.d'));

This might help someone else :)

Post a Comment for "Dynamic Access To An Array In Javascript"