Vue - Find matching data in an array of objects and render it on the page

I have a Vue.js data array that contains information about counties in the UK. I want to create links between related county pages based on the data in the array.

To achieve this, I need to loop through the main county object and compare the items in the closeby field with the county names.

Example of my current data structure:

createApp({
    data() {
        return {
            counties: [
                {
                    county: 'Bedfordshire',
                    link: 'example.com/link',
                    districts: [
                        { authority: "Bedford" },
                        { authority: "Luton" }
                    ],
                    cities: false,
                    coastal: false,
                    flag: true,
                    closeby: [
                        { county: 'Cambridgeshire' },
                        { county: 'Hertfordshire' },
                        { county: 'Buckinghamshire' },
                        { county: "Northamptonshire" }
                    ]
                },
                ...
            ],
        }
    }
}).mount('#app')

I have displayed the related counties like this:

<span v-for="(neighbour, index) in county.closeby">
    <span v-if="index !== 0 && index !== county.closeby.length - 1">, </span>
    <span v-if="index == county.closeby.length - 1 && county.closeby.length > 1"> and </span>
    {{ neighbour.county }}
</span>

Now, I want to include the links of each county alongside their names, like:

Cambridgeshire (example.com/link1), Hertfordshire (example.com/link2), Buckinghamshire (example.com/link3), and Northamptonshire (example.com/link4)

How can I compare the items in the closeby field with the links for each county in the counties array so that I can display them correctly, considering the varying number of items in closeby?

Answer №1

If I understood correctly, you should look for the link in the counties array:

const app = Vue.createApp({
  data() {
    return {
      counties: [
          {county: 'Bedfordshire', link: 'example.com/bedfordshire', districts: [{authority: "Bedford" },{authority: "Luton"}], cities: false, coastal: false, flag: true, closeby: [{county: 'Cambridgeshire' }, { county: 'Hertfordshire' }, { county: 'Buckinghamshire' }, { county: "Northamptonshire" }]},
          {county: 'Cambridgeshire', link: 'example.com/cambridgeshire', districts: [{authority: "Bedford" },{authority: "Luton"}], cities: false, coastal: false, flag: true, closeby: [{county: 'Bedfordshire' }, { county: 'Hertfordshire' }, { county: 'Buckinghamshire' }, { county: "Northamptonshire" }]},
          {county: 'Hertfordshire', link: 'example.com/hertfordshire', districts: [{authority: "Bedford" },{authority: "Luton"}], cities: false, coastal: false, flag: true, closeby: [{county: 'Bedfordshire' }, { county: 'Cambridgeshire' }, { county: 'Buckinghamshire' }, { county: "Northamptonshire" }]},
          {county: 'Northamptonshire', link: 'example.com/northamptonshire', districts: [{authority: "Bedford" },{authority: "Luton"}], cities: false, coastal: false, flag: true, closeby: [{county: 'Bedfordshire' }, { county: 'Cambridgeshire' }, { county: 'Buckinghamshire' }, { county: "Hertfordshire" }]},
      ],
    }
  },
  methods: {
    getLink(county) {
      return this.counties.find(c => c.county.toLowerCase() === county.toLowerCase())?.link
    }
  }
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <div v-for="(county, i) in counties" :key="i">
    <span v-for="(neighbour, index) in county.closeby" :key="index">
      <span v-if="index !== 0 && index !== county.closeby.length - 1">, </span>
      <span v-if="index == county.closeby.length - 1 && county.closeby.length > 1"> and </span>
      <a :href="getLink(neighbour.county)" :title="getLink(neighbour.county)">{{ neighbour.county }}</a>
    </span>
  </div>
</div>

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

What is the best method to incorporate filtering in a CRUD table?

Frontend code: // Importing necessary components and libraries import React, { Component, useState, useEffect } from "react"; import Navbar from "../Navbar/Navbar.js"; import BarChart from "../BarChart/BarChart"; import { Chart, Tooltip, CategoryScal ...

Unlocking the secret to obtaining durable identity provider tokens for JavaScript in web browsers

Currently, I am working on implementing browser-side JavaScript code for login with Facebook, Amazon, Twitter, and Google using Cognito. I have reached a point where I am able to obtain client tokens for all four platforms. However, the issue is that thes ...

Sending an object as a prop in React component

I have a function class: function TopicBox({topicName, article1}) { return ( <div className="TopicBox"> <h1>{topicName}</h1> <div className="topicDivider" /> <Ar ...

Tips for verifying a login modal on an asp.net webforms using jQuery?

I am currently working on an asp.net webpage that utilizes a modal bootstrap for user login. Upon clicking the Login button, it should authenticate the user and initiate a server-side method called "ExportToZip" to download a zip file. My issue lies in ens ...

Struggling with this mixed content problem

Encountering a problem while loading a js file: https://code.jquery.com/jquery-1.11.1.min.js, which is being loaded on my webpage in this manner: <script src="https://code.jquery.com/jquery-1.11.1.min.js"></script> Upon loading my webpage, an ...

Add value to a progress bar over time until it reaches the designated timeout

I'm struggling to implement a loading bar with a fixed timeout requirement. The goal is for the bar to be completely filled within 5 seconds. While I have successfully created the HTML and CSS components, I am facing difficulty in developing the JavaS ...

Adjust the size of the event bar on the FullCalendar resourceTimeline view

In my implementation of FullCalendar v6, I am displaying 6 months worth of data in the calendar, with each slot representing a one-month period. The issue I am facing is that when creating an event spanning 10 days, it currently takes up the entire width o ...

"Enjoy a unique browsing experience with a two-panel layout featuring a fixed right panel that appears after scrolling

I am facing difficulty in designing a layout with two panels where the left panel has relative positioning and the right panel becomes fixed only after a specific scroll point. Additionally, I need the height of the right panel to adjust when the page scro ...

Selenium and AngularJS patiently wait before carrying out specific actions

I have been using selenium to test an AngularJS application and I am encountering an issue where I am unable to perform any actions on the page until it is fully loaded. Although I have considered using Thread.sleep(), I am aware that this is not the most ...

The npm error message indicates that there is an issue with the transpileDependencies.map function

Every time I attempt to execute my program, this error pops up: https://i.stack.imgur.com/ANA0z.png Even after uninstalling and reinstalling node, the error persists. ...

You cannot employ typed arguments in combination with Typescript within the VueJS framework

I'm struggling to develop a typescript vue component with some methods. Here is the script snippet. <script lang="ts"> import Vue from 'vue'; export default Vue.extend({ methods: { check(value: number) { console.log(valu ...

Change the text of a button by using an input field

How can I dynamically update button text based on input field value? <input class="paymentinput w-input" type="tel" placeholder="0" id="amount-field"> <button id="rzp-button1" class="paynowbutton w-button">Pay Now</button> I want the bu ...

What is the best way to pass my request data to my $scope variable?

I'm currently facing a challenge with this particular topic. My goal is to add the response data that I retrieve from Express to my angular $scope and then direct the user to their profile page. This is how my Controller Function is structured: $sc ...

Finding the Key in a Multidimensional Array using PHP

I am currently working with the following array structure: Array ( [carx] => Array ( [no] => 63 ) [cary] => Array ( [no] => 64 ) ) I am trying to figure out how to find t ...

Maximizing Angular and Require's Potential with r.js

I'm facing some challenges while setting up r.js with require in my Angular application. As I am new to AMD, solving this issue might be a simple task for someone experienced. However, I need to maintain the current directory structure as it allows me ...

jQuery and HTML: Need help enabling an <input> or <select> element?

Currently, I am using Mozilla Firefox 14.0.1 and Google Chrome 20.0.1132.57 (which I believe is the latest version). The code I am working with looks like this: http://jsfiddle.net/SVtDj/ Here is what I am trying to accomplish: Type something into inpu ...

What steps can I take to ensure that the browser prints out a PDF copy of a webpage?

Imagine you have a website page saved as example.html, and also a printable file named example.pdf. Is there a way to prompt the browser to open and print example.pdf instead of example.html when users attempt to print? If this isn't achievable, how ...

Need some assistance with Javascript Ajax? Specifically, dealing with multiple values?

My goal is to asynchronously post an array of messages using this code. Despite my efforts, I've encountered a challenge where it doesn't only post the four items in the array but also adds gibberish text. Additionally, there seems to be an issue ...

What is the purpose of enclosing an Angular app within a function?

As I delve into learning Angular, I've encountered a recurring snippet in the app.js file across various resources: (function () { \\\myAngularModules })(); Despite its prevalence, the explanation provided is often just ...

Showing formatted JSON (Large Object) on an HTML page

Having trouble displaying formatted JSON in an HTML page, especially when dealing with larger objects (an array of objects). The current method involves using JSON.stringify(data) to display the JSON object upon receiving a response from the server. The P ...