Get dynamically object path from an array

I’m desperately trying to find a solution on how to get the path to an object by extracting values from an array but unfortunately couldn’t find an answer online.

I have the following dataset.

dataLoad: {
     "users": [
        "id": 1,
        "firstName": "Terry",
        "lastName": "Medhurst",
        "address": {
                "city": "Louisville",
                "coordinates": {
                    "lat": 38.1343013,
                    "lng": -85.6498512
         "id": 2,
         "firstName": "Sheldon",
         "lastName": "Quigley",
         "address": {
                "city": "Washington",
                "coordinates": {
                    "lat": 38.867033,
                    "lng": -76.979235
        } ],

arr: [],
path: '',

Since the value of arr is dynamic and its length is unknown, I need to form the full path dynamically so that I can extract the value from dataLoad.


arr: ["users", "address", "coordinates"],
// path = users.address.coordinates
arr: ["users", "address", "coordinates", "lat"],
// path =
arr: ["users", "address"],
// path = users.address

User case:

<div v-for="(item in dataLoad)">{{ item[path] }}</div>

Thank you!

you can use lodash _get() to retrieve value by path which is array format.

docs here: Lodash Documentation

That helped! Thank you!
However, adding lodash functions I face another problem.

[Vue warn]: Property "_" should not start with _ which is a reserved prefix for Vue internals. at <App>

I googled the error, and the recommendation is to use $data in front but it doesn’t help. I’m using CDN both for lodash and vue.

Did you add the function as a method in the Vue component? Then simply rename the function to something else in the Vue component, so it doesn’t start with _.

I call Lodash functions from inside HTML elements. Here’s an example.

<li v-for="(n, i) in listSize" :key="i">
    <span> {{ _.isArray(jsonItems[0]) ? _.get(jsonItems[0][i], dataLoadSplit) : _.get(jsonItems[0][dataLoadSplit[0]][i], _.drop(dataLoadSplit, 1) )  }}</span>

Wondering if moving Lodash functions into methods is the best way to avoid these warning errors? As I understand it, this means having a separate method for each required Lodash function, which adds quite a few additional methods.

You can also do the renaming when you import _, or just import the things you need, like:

import { isArray } from 'lodash';

Then you can use just isArray in the code, instead of _.isArray.