Learn how to extract substrings from a variable within an API using Vue.js

Exploring VueJs for the first time and looking to split a string by comma (,) retrieved from an API into separate variables. The data is coming from a JSON server.

"featured-property": [
    {
        "id": "1",
        "name": "Property 1",
        "address": "Address Property 1",
        "geo": "0.5307596, 101.4461512"
    },
    {
        "id": "2",
        "name": "Property 2",
        "address": "Address Property 2",
        "geo": "0.5055971577036701, 101.452919"
    }

The goal is to parse the "geo" values, store them in variables "lat" and "lng", and use them with vue2-google-maps. Axios is being used to fetch the API.

export default{
    name: 'PropertyDetail',
    data(){
        return{
            property: [],
        }
    },
    methods: {
        setProperty(data){
            this.property = data
        },
    },
    mounted() {
        axios
        .get("http://localhost:3000/featured-property")
        .then((response) => this.setProperty(response.data))
        .catch((error) => console.log(error))
    }
}

Seeking guidance on how to achieve this task using VueJS. Any advice would be appreciated!

Answer №1

If you have an array of objects from JSON data, you can use a function like the following to manipulate the data:

updateObject: function(obj){
  var coordinates = obj.location.split(', ');
  obj["latitude"] = coordinates[0];
  obj["longitude"] = coordinates[1];
}

In your setAttributes method, you can utilize this function as shown below:

setAttributes(data){
   var updatedData = [];
   var self = this;
   data.forEach(function(item){
      updatedData.push(self.updateObject(item));
   })
   this.attributes = updatedData;
}

The updateObject function will modify the passed-in object directly. However, it is recommended to create a new variable with the modifications and return that instead.

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

Route parameters do not function correctly with computed properties

I'm facing an issue with my getter function that stores all products. When I try to retrieve a single product dynamically based on this.$route.params.id, it doesn't return any value. The code works fine when I navigate to a specific product, but ...

Retrieve a specific value in HTML <a> tag using JavaScript-Ajax in Django

I am currently working with Python 3 and Django. Within my HTML code, I have the following: {% for category in categories() %} <li class="c-menu__item fs-xsmall"> <a href="#" id="next-category"> {{ category}} & ...

"Failure to manipulate the style of an HTML element using Vue's

<vs-tr :key="i" v-for="(daydatasT, i) in daydatas"> <vs-td>{{ daydatasT.Machinecd }}</vs-td> <vs-td>{{ daydatasT.Checkdt }}</vs-td> <vs-td>{{ daydatasT.CheckItemnm }}< ...

Tips for using ng-repeat in AngularJs to filter (key, value) pairs

I am trying to achieve the following: <div ng-controller="TestCtrl"> <div ng-repeat="(k,v) in items | filter:hasSecurityId"> {{k}} {{v.pos}} </div> </div> Code snippet for AngularJs: function TestCtrl($scope) { ...

Please refrain from utilizing MUI - useGridRootProps outside of the DataGrid/DataGridPro component

When we click on "Filter" in the context menu of our DataGrid, we encounter this error. We are working on implementing a component hierarchy for the DataGrid as follows: MigrationJobTable.tsx: return ( <div data-testid='migrationJobTa ...

Is there a way to simultaneously apply the :active pseudoclass to multiple elements?

<div id="a">A</div> <div id="b">B</div> <div id="c">C</div> <style> #a, #b, #c { height: 100px; width: 100px; background-color:red; font-size: 100px; margin-bottom: 20px; } ...

Running complex operations within a sorting function just once

I am facing the challenge of sorting an array of objects based on multiple date fields, with the added complexity of excluding certain dates depending on the category. In order to optimize performance, I want to minimize the number of times the getUsefulJo ...

Implementing a click function that toggles between adding and removing a class, keeping track of the number of clicks, and utilizing localStorage to prevent repeated clicking in the

Hi there! I'm currently working on a simple widget that features a clickable icon and a counter next to it. When the icon is clicked, it should toggle between an empty heart and a filled heart using addClass/removeClass. Additionally, each click incr ...

My Vue frontend project is encountering an error during compilation that states "this relative module module was not found."

I have created a vue frontend to interact with my spring backend, which is working well. However, when I compile the frontend, it compiles to 98% and shows an error message: ERROR Failed to compile with 1 error 11:24:51 The relative module was not foun ...

What is the best way to delete a nested document within an array in MongoDB by referencing its _id?

I am trying to remove a nested object from an array of objects called createdEvents if the createdEventId matches the id I pass to it. This is the JavaScript query I am using: db.collection("users").updateOne({ _id: userId }, { $pull: { createdEv ...

I am having trouble setting an object in the state using React hooks

When assigning an initial value to a state as null, the setState method does not hold the value when assigned. Calling an API in useState returns an object which cannot be directly put into setState. const [userProfile, setProfile] = useState(null); cons ...

Make a call to a remote node.js server using an ajax request

My setup involved a basic nodejs server (including CORS) : var express = require('express'); var app = express(); var http = require('http').Server(app); var io = require('socket.io')(http); var port = 8001; http.listen(port, ...

Having trouble displaying the selected button in React

Is it possible to include multiple functions within an onclick event? Check out the code snippet below: import React from 'react'; class Counter extends React.Component { state = { count: 0, inc: 'Increment', ...

When attempting to access the state within an action, the state appears to be

Upon refreshing the webpage (with vuexPersistedState), I am trying to access my state within an action using the following code snippet: updateOuterValue: ({ commit }, data) => { console.log(state); ... } Despite having ...

Error encountered when uploading an image using an inertiajs form.post in Laravel 8 due to failed mime image validation

Laravel version: 8.82.0 When using inertiajs, I am facing an issue while uploading an image through a post request using the form.post method. The controller receives image data as shown in the image below: https://i.sstatic.net/pMFTu.png This is my sim ...

What is the best way to get the latest props in the midst of an async function?

There's a fascinating open-source project called react-share, where the ShareButton component offers a prop known as beforeOnClick for customization. I've utilized this beforeOnClick to upload images to our CDN before sharing, ensuring that only ...

What are some strategies for improving the speed and efficiency of traversing an XML file with AJAX?

I am currently working with an XML file structured like this: <UUT> <DKBFile>091750</DKBFile> <part> <name>FL_U1</name> <xcoord>439</xcoord> <ycoord>132</ycoord> <width>55</width ...

Alert Box Displays Variable Name Instead of Label Name in Form Validation - MM_validateForm()

Looking at the screenshot, you can see variable names such as "email_address", "email_message" and "email_subject". I would like these to be displayed as "Email", "Message" and "Subject" instead. The validation in this form is done using MM_validateForm() ...

Refresh the Content of a Page Using AJAX by Forcing a Full Reload

I have a webpage that automatically updates a section using jQuery AJAX every 10 seconds. Whenever I modify the CSS or JavaScript of that page, I would like to include a script in the content fetched via AJAX to trigger a full page reload. The page is ac ...

Node-powered Angular

Currently working on setting up client-side routing with AngularJS and Node. Ran into some issues along the way. EDIT After making changes to my code based on recommendations from @PareshGami, following https://github.com/scotch-io/starter-node-angular, I ...