Viewing the availability of various locations within a JSON table based on the user's specific locale

I am working with a JSON table:

[
  {
    "fr": { "name": "chien", "name_plurial": "chiens" },
    "en": { "name": "dog", "name_plurial": "dogs" }
  },
  {
    "fr": { "name": "chat", "name_plurial": "chats" },
    "en": { "name": "cat", "name_plurial": "cats" }
  },
]

In my .vue file, I import this data and use v-for to display it:

<template>
<div>
          v-for="(specie, index) in species"
          :key="index"
          :label="specie.en.name | capitalize"
          :value="specie.en.name">
</div>
</template>

import Species from '~/static/data/species.json'

export default {
        data() {
            return {
                species: Species,
            }
        },
}

Now, I want to dynamically retrieve the locale based on the language of my user user.lang.

Can you help me achieve this?

Thank you!

Answer №1

To show the local language you desire, simply include specie[${local}] in your code.

For example: en

new Vue({
  el: "#app",
  data: {
         local: "en",
      species: [
        {
          fr: { name: "chien", name_plurial: "chiens" },
          en: { name: "dog", name_plurial: "dogs" }
        },
        {
          fr: { name: "chat", name_plurial: "chats" },
          en: { name: "cat", name_plurial: "cats" }
        }
      ]
  },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<span><b>{{local}}</b> language</span>
  <ul>
      <li v-for="(specie, index) in species" :key="index">{{specie[`${local}`].name}}</li>
    </ul>
</div>

Answer №2

If you're unsure, one possible solution is to utilize the filter() method within the return statement.

Consider the code snippet below:

const user = {
  lang: 'en'
};
const species = [
  {
    "fr": { "name": "chien", "name_plurial": "chiens" },
    "en": { "name": "dog", "name_plurial": "dogs" }
  },
  {
    "fr": { "name": "chat", "name_plurial": "chats" },
    "en": { "name": "cat", "name_plurial": "cats" }
  },
];

const result = species.map(e => {
  let elem = {};
  elem[user.lang] = e[user.lang]
  return elem;
});

console.log(result);

I trust this provides some insight to your query!

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

Mapping JSONP responses for jQuery UI autocomplete

Attempting to implement jqueryUI autocomplete. After alerting the response, it shows: ([ { "id": "test", "label": "test", "value": "test" } ]); However, when trying to map the result, the dropdown remains empty. Here is the code being used: <script> ...

Is there a way to dynamically create a property and assign a value to it on the fly?

When retrieving data from my API, I receive two arrays - one comprising column names and the other containing corresponding data. In order to utilize ag-grid effectively, it is necessary to map these columns to properties of a class. For instance, if ther ...

Tips for accessing a variable value within a JavaScript function

I am currently facing an issue where I am unable to retrieve a variable from a JavaScript function and use it outside of the function. While I can successfully output the variable value inside the function, I am struggling to access it elsewhere in my sc ...

Styling limitations encountered when using lang="scss" with scoped css

My current project involves using Quasar and I am attempting to style the first column of q-table: <style lang="scss" scoped> td:first-child { background-color: #747480 !important; } </style> Unfortunately, this code does not seem to have a ...

Encountering problems with displaying the index value in *ngFor directive in Angular 5

I am encountering a problem with rendering the index of *ngFor directive for a specific scenario as described below. Suppose we have an array of objects like this: this.temp = [ {name:'John',age:24,visibility:'visible'}, {name:&ap ...

Retrieving specific value from a Parent Controller in AngularJS using UI Router

I have a request to display the value stored in $scope.resAVal on my index.html page. This value is accessible within the RootCtrl. index.html <!DOCTYPE html> <html ng-app="plunker"> <head> <!-- any required JavaScript librarie ...

"Loopback's MongoDB is successfully retrieving data for GET requests, however, it is not providing

myModel.remoteMethod('getName', {accepts: {arg: 'id', type: 'Number', required: true}, http: {path: '/customer/:id', verb: 'get'}, returns: {arg: 'results',type: 'Obje ...

What is the best method to create random coordinates that fall outside of the circle located within a rectangular area?

Suppose the following scenario: A rectangular area with dimensions length l and breadth b A circle with a radius r The circle is positioned inside the rectangular area as depicted in the image below Check out the image here - Red areas show expected even ...

Challenges with Implementing Slide Out Menus

Creating a page with multiple slide out menus- one on the right, left, and bottom. Currently facing a few issues: The content div is not moving to the right when the menu is selected. The menu icon moves but the div stays put. Attempting to have them bot ...

failing to run a Docker image

I am encountering an issue while trying to run the docker image. I am unable to access it and keep getting a permission denied error, as shown below. #base image FROM selenium/standalone-chrome # Install Node.js RUN sudo apt-get update RUN sudo apt-get ...

Creating a brushstroke on an image with JavaScript

I need to create an interactive image where users can mark a point and draw a line by clicking and dragging the mouse. Once the line is drawn, I want to display its dimensions in millimeters or centimeters when the user clicks on the image again. Essential ...

Trying to retrieve a local JSON file using Axios or Fetch resulted in a peculiar response format and an unexpected JSON token error, prompting me to attempt

I encountered an issue with my axios response (or fetch) where it returned plain text as a string instead of the JavaScript map I was expecting. When I tried using JSON.parse() or .json() from fetch, I received the following error: Uncaught (in promise) ...

Achieving a reset for a form is essential for ensuring its

After creating a contact form, I encountered an issue where if a field is left empty or an invalid email address is entered, the form stops sending. Even after attempting to resend the information, the form remains unresponsive. Any suggestions on how to r ...

Arrange divs adjacent to each other without any gaps in between

My HTML code includes elements from Twitter Bootstrap and AngularJS framework. <div class="item item-custom-first"> <select class="form-control" style="display:inline; float:right" ng-model="requestdata.units ...

Utilize computed fields in Parse Object queries

Currently, I am working on developing a Parse Server API for a cooking-centered social network. One of the key features I am focusing on is creating a function that retrieves recipes. I want this function to be able to display calculated fields such as t ...

Submit your Alpaca info without leaving this page!

Currently, I am in the process of constructing a form using PHP and ALPCA, which involves jquery and ajax. However, I seem to be encountering some difficulty when it comes to file submission while staying on the same page. Despite attempting various recomm ...

Tips for transferring a JavaScript variable to a Java servlet using the doPost method

I am working with an HTML table that contains dropdowns. When a user clicks on a dropdown, I store the column name and corresponding row (billdate) in a variable. Now, my goal is to pass this variable to my Java servlet's doPost method and then use it ...

The function does not yield any result

import { Injectable } from '@angular/core'; export class Test { public id: number; public name: string; public fid: number }; export const TESTS2: Test[] = [ {id: 1, name: 'Lion', fid: 1}, {id: 2, name: 'Tiger', fid: 1 ...

Does the delegated 'on' handler make any mention of the chosen element?

Is there a way to retrieve the selected element when using jQuery's on method within the handler, instead of the event target? In this context, none of the following code refers to the body element: $('body').on('click', 'h1& ...

Changing a get request to a post request: A step-by-step guide

I have been utilizing the following script: $(document).ready(function() { $("#test-list").sortable({ handle : '.handle', start: function(){ $("#success-result").html("loading...."); }, update : function ( ...