Is it possible to access a sub property using a dot string in Vue 3?

Given a Vue 3 proxy object structure as shown below:

<script>
export default {
  name: "test",
  data() {
    return {
      users: [{
        "id": 1,
        "name": "Leanne Graham",           
        "address": {
          "street": "Kulas Light",             
          "geo": {
            "lat": "-37.3159"
          }
        }
      },
        {
          "id": 2,
          "name": "Ervin Howell",             
          "address": {
            "street": "Victor Plains",               
            "geo": {
              "lat": "-43.9509"             
            }
          }
        }],
      street: "address.street",
      lat: "address.geo.lat"
    }
  }
}
</script>

Is this method of accessing the data valid, or is there a better approach?

<template>
  <ul>
    <li v-for="user in users">
      street: {{ user[street] }} <br>
      lat: {{ user[lat] }}
    </li>
  </ul>
</template>

Answer №1

If I understand correctly, you can access object properties using dot notation:

const app = Vue.createApp({
  data() {
    return {
      users: [
        {"id": 1, "name": "Leanne Graham", "username": "Bret", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1f4c76717c7a6d7a5f7e6f6d7673317d7665">[email protected]</a>",        "address": {"street": "Kulas Light", "suite": "Apt. 556", "city": "Gwenborough",          "zipcode": "92998-3874", "geo": { "lat": "-37.3159", "lng": "81.1496"}}},
        {"id": 2, "name": "Ervin Howell", "username": "Antonette", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="27744f46494946674a424b4b53514354095544534e1945474e494113595b">[email protected]</a>", "address": { "street": "Victor Plains", "suite": "Suite 879", "city": "Wisokyburgh", "zipcode": "90566-7771", "geo": { "lat": "-43.9509", "lng": "-34.4618"}}},
        {"id": 3, "name": "Ervin Howell", "username": "Antonette", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="22714a434c4c43624f474e49515352477d5452">[email protected]</a>", "address": { }},
        {"id": 4, "name": "Ervin Howell", "username": "Antonette", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="43102b222d2d22032e262f292730254f262e">[email protected]</a>", "address": { "street": "Victor Plains", "suite": "Suite 879", "city": "Wisokyburgh", "zipcode": "90566-7771", "geo": {}}}
        ],
      street: "address.street",
      lat: "address.geo.lat"
    }
  }
})
app.mount('#demo')
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5325263613607d617d616a">[email protected]</a>/dist/vue.global.prod.js"></script>
<div id="demo">
  <ul>
    <li v-for="user in users">
      street: {{ user.address?.street }} <br>
      lat: {{ user.address?.geo?.lat }}
    </li>
  </ul>
</div>

Answer №2

To extract a value from a string path containing dots, you can utilize utilities like Lodash's get function or explore alternatives in this related discussion.

Here is the function:

fetchAddress(data) {
  return _.get(data, this.address)
}

And how you would use it:

address: {{ fetchAddress(customer) }}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering an ETIMEDOUT error while sending out large (10k) post requests with axios.all in a Node

I have implemented axios.all to make simultaneous post calls. Below is the code snippet: let postUrls = []; data.forEach(item => { const itemData = { stream: stream_name, key: item.serialNumber, addr ...

Navigating through intricate JavaScript object

I need help figuring out how to access the "description" property of a JSON object I received from an API endpoint. The object looks like this: - "description" : "Dorian Market 1"? let markets = { "result":[ { "townId" : "MEBD", "stor ...

Learning the best practices for incorporating publish and subscribe in Meteor JS is crucial for achieving efficient

I need some guidance on my implementation of publish and subscribe in Meteor JS. I am new to this and seeking help to ensure that I am doing it correctly. If you require more information about my code, I am happy to provide additional source code. Despit ...

How to use expressjs to fetch an image from a URL and show it on a webpage

I am currently running an image API from my home server, and I am working on creating a cloud-hosted page that will retrieve the image in the backend and display it, adding a layer of abstraction. My goal is to achieve the following: index.js var express ...

"An issue with preventing default behavior when clicking on a jQuery element

I need some assistance preventing a JQuery onclick function from scrolling the page to the top. I have tried using preventDefault() without success. You can find the code on this website: Below is the code snippet that I am currently using: $( document ...

There seems to be a problem with playing a UI video, but interestingly it functions

I am facing an issue with playing MP4 (HD) videos on the UI that I receive from the Django backend. My setup involves using normal Javascript on the frontend and Django on the backend. Here is a snippet of the backend code: file = FileWrapper(open(path, &a ...

Using AJAX to refresh a div upon submitting a form, instead of reloading the entire page

My SQL database generates a table that remains hidden until the search button is clicked to display the results. I want to use ajax to update the table without refreshing the entire page. Currently, when the page refreshes, the table reverts back to being ...

The asynchronous callbacks or promises executing independently of protractor/webdriver's knowledge

Could a log like this actually exist? 07-<...>.js ... Stacktrace: [31m[31mError: Failed expectation[31m [31m at [object Object].<anonymous> (...06-....js)[31m[31m[22m[39m It seems that something is failing in file -06- while I am processin ...

Error 4 encountered when attempting to upload files using Ajax to a PHP server

On my website, there is a form that looks like this: <form style="width:100%; clear:both; margin-top:50px; background:#fff; border:1px solid green" id="upload_form" enctype="multipart/form-data" class="form" action="" method="post"> <fieldse ...

Repurposing React key usage

section, I am curious to know if it is standard practice to reuse a React key from one component to another. For instance, in the Row component, the key obtained from the Column component is reused for mapping the children of Row. const Table = props =& ...

Issue with my lazyloading extension for Mootools

Seeking to create a plugin for sequential image downloads using MooTools. Assuming there are images with the img tag inside a div with the class imageswrapper. The goal is to download each image in order, one after the other until all images are loaded. ...

Arranging CouchDB/Couchbase view based on the quantity of keys

Looking to create a view that displays the top 10 tags used in my system. While it's simple to get the count using _count in the reduce function, the list is not sorted by the numbers. Is there a way to accomplish this? function(doc, meta) { if(doc ...

The discrepancy between the heights of a div using Jquery and JavaScript

There is a container div encompassing all the site's content, which dynamically stretches. Additionally, there are multiple other divs that also stretch using the same method as in 20 other sites. Despite trying various methods with jQuery and JavaSc ...

What is the method in Vue.js for receiving notifications when a property's value is accessed?

Currently, I am working on a project using Vue.js and facing a challenge with dependencies. In my data object, there is a boolean property that I need to track whenever it is accessed or used so that I can make changes to other properties before the boolea ...

JavaScript code snippet to remove a specific element from an array and store it in an object

I am looking to convert an array into an object, where each item in the array is separated into categories as shown below. let a=['monkey: animal','John:human', 'Rob:human', 'donkey:animal'] I expect the output to b ...

Surprising 'T_ENCAPSED_AND_WHITESPACE' error caught me off guard

Error: An error was encountered while parsing the code: syntax error, unexpected character (T_ENCAPSED_AND_WHITESPACE), expected identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in C:\wamp\www\html\updatedtimel ...

What is the best way to streamline a state-dependent getter, with a focus on adhering to SOLID principles?

Is there a more user-friendly way to retrieve different data based on the type in my Angular component? I'm considering separating the component into two: one for phone and one for email. However, I'm concerned about duplicating most of the logi ...

jQuery does not cache Ajax requests by default

I have implemented the following code to make an AJAX request. I am trying to determine if the requests are being cached by using the Chrome developer tools. However, when I check the request tab, I notice that all data is always being pulled from the serv ...

Experiencing slow loading times with a Next.js app in the development environment

Currently, I am in the process of building a Next.js application and I have noticed that it takes quite a long time to load in the development environment. At the start, the page becomes unresponsive and if I cancel the request, it stops loading altogeth ...

What is the best way to populate an array with JSON data using jQuery?

As a newcomer to jQuery, I decided to experiment with the getJSON function. My goal was to extract the "id" section from a JSON file and store it in an array called planes using jQuery. This array would then be utilized in an autocomplete function to popul ...