What is the best way to transform a List<Pair<String, String>> to a List<String> using JavaScript?

Here is the data output structure:

Map<String, List<Pair<String, String>>>

    "testdata": [
        {
            "1.0": "True"
        },
        {
            "1.1": "False"
        }
]

I now need to present this data on the UI in the format

"testdata":["1.0","1.1","1.2"]
, where I specifically want to fetch only the first elements from each Pair and place them in the structure
Map<String, List<String>>

Can you provide me with a javascript code snippet that accomplishes this task?

this.previousData = versions.filter(v => v !== this.version).map(item => ({ text: item, value: item }))

How can I adjust this code to achieve the desired output of

"testdata":["1.0","1.1","1.2"]
?

Answer №1

If you want to achieve a similar outcome, consider implementing the following approach:


// The assumption is that each array item contains only one key, or the first key indicates the version

this.previousData = 
    versions
     .filter(v => v !== this.version)
     .map(item => Object.keys(item)[0])

// Alternatively, as recommended by MikeT, if the data structure adheres to the following format:
// [
//  { "v1": "some value 1" },
//  { "v2": "some value 2" },
//  ... generally --> { "version": "some value" }
// ]
// You may also try this method
this.previousData = 
    versions
     .filter(v => v !== this.version)
     .map(item => Object.keys(item))
     .flat()


Answer №2

It seems like your question is a bit vague in terms of the element you're struggling with.

If you want to retrieve the data:

async fetchData()
{
    const response = await fetch("<<insert URL from your Java service here>>")
    return await response.json();
}

To customize the format of the data:

formatData(json){
    return json.testdata.map((item) => Object.entries(item).map(([key, value]) => key)).flat()
}

And for displaying in Vue:

<template>testdata:{{testdata}}</template>
<script>
...
     methods:{
        async loadData(){
            const temp = await fetchData()
            this.testdata = formatData(temp)
        }
     }
...
</script>

Using Object.entries will convert an object into a tuple array, so

{"1.0":"True", "1.1":"False"}
will transform into
[["1.0", "True"], ["1.1": "False"]] 
, allowing you to extract the keys using tuple decomposition.

If you only need keys and not values, Object.keys() can also be used. However, as the context was unclear, I provided the more versatile option.

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

Sorting through mongoose information on the front end using EJS depending on a dropdown pick

Beginner embarking on my inaugural project here. I have developed 2 Mongoose schematics and models for managing categories and products. The products are nested within the corresponding categories model. Using Node and Express, I successfully sent all ca ...

What is the best way to extract "true" values from an array and store them in a new array during iteration?

I am currently enrolled in a Codecademy course and I am facing a roadblock. My main goal is to gain a solid grasp of JavaScript. The current task at hand is as follows: "There is an array of unnecessary words. Your goal is to iterate over the array and fi ...

Comparing JSON and JavaScript object arrays: Exploring the differences in outcomes and strategies for achieving desired results

Although it's not valid JSON, I've found that by declaring this as a variable directly in my code, I can treat it like an object. <script> // this will result in object var mydata = { users: [{ person: { ...

The issue with Postman Express.js Response Body not displaying any content is quite common

I've been struggling with this issue for a whole day and I just can't seem to find a solution. My node app is extremely simple. const express = require("express"); const port = 3001; const app = express(); app.use(express.json()); app.pos ...

The password reset feature using bcrypt is malfunctioning, as headers cannot be modified once they have been sent to the client

After developing a reset password function, the code appears as follows: router.get('/reset/:id',function(req,res,next){ User.findOne({'resetToken': req.params.id.trim()}) .exec(function(error, user){ if (error) ...

Can I change the name of an item in ngRepeat?

When repeating in a view: ng-repeat="item in list" In some scenarios, the 'item' looks like this: { "name": "john", "id": 1 } While in others, it appears as: { "value": { "name": "john", "id": 1 } } Is there a way to rena ...

Flask Server produces a response with a considerable delay when accessed through AJAX

I am currently running 2 servers on localhost, each with different ports. One of them is a basic flask server in Python and its code is provided below: from flask import Flask,jsonify from flask_cors import CORS app = Flask(__name__) CORS(app) @app.rout ...

Tips for accessing data in Vue.js pug templates:

Essentially, my goal is to create a permalink from an event name. I am able to retrieve the value from the event name using v-model successfully, but I'm having trouble figuring out how to input the converted permalink into another input box in pug. ...

Vanishing Items - Three.js CanvasRenderer

I'm in a bit of a pickle here. I can't figure out why my objects are disappearing when using the canvas renderer. Strangely enough, everything works fine with the webGL renderer. Unfortunately, I need to make sure this displays properly on mobile ...

Replicate the array multiple times and combine them into a single flat array

I have a four-element array that I need to copy to another array four times. I achieved this by concatenating the array four times. Here is what I tried: let demoProperties = [] .concat(fourDemoProperties) .concat(fourDemoProperties) .concat(fourDe ...

Utilizing a directive in contexts beyond a component

I have developed a popover module that consists of two components and three directives. However, I am encountering an issue where I am unable to utilize the directives outside of the main component. Whenever I try to do so, I face an editor error stating: ...

JavaScript - Issue arises when evaluating the sine of complex numbers of large magnitudes

I have developed a unique sine calculator that can handle the evaluation of the sine of complex numbers by utilizing polar coordinates and computing part of the infinite series defining the sine function. The calculator performs smoothly when dealing wit ...

Creating dynamically generated nested text inputs with individual v-model bindings upon the clicking of a button

As a newcomer to vuejs, I am attempting to create nested textboxes dynamically with the click of a button. For a clearer explanation, please refer to this jsfiddle link: https://jsfiddle.net/avi_02/qLqvbjvx/ Let's use an analogy to grasp the iss ...

Creating custom validation in Vuetify for password confirmation is essential in ensuring that

While developing a Vue.js template, I encountered a scenario on the sign-up page where I needed to compare passwords during user registration. To achieve this, I implemented a custom validation rule in the code snippet below: <v-text-field label=" ...

Verify if the v-dialog is currently active and pause the audio playback

I am looking to implement a watcher on the v-dialog to stop audio files from playing when the dialog is open. Typically, I would use v-model="dialogVisible" and then add a watch function. However, because I have multiple dialogs, I am using v-model="media. ...

Managing different authentication methods for a single user on Firebase: Tips and Strategies

Currently, I am in the process of developing an authentication system utilizing Firebase. My aim is to incorporate email/password, Google, and Facebook as sign-up and sign-in methods. Initially, everything runs smoothly when a user signs up using each met ...

Executing PHP Functions with Script Tags

I am trying to use PHP to output the <script></script> tag. Here is the code I am using: <?php echo "test"; echo "<br>"; echo '<script src="http://mywwebiste./mycode.js" type="text/javascript& ...

Utilize Protractor to extract the text within a specified span element

Is it possible to check if the text of the span within the button is "Vigente" using expect and Jasmine? If so, how can I achieve this? <button _ngcontent-hke-28="" class="btn btn-success disabled" tabindex="-1"> <span _ngcontent-hke-28="" class= ...

Using Redux with Next.js to implement getStaticPaths

Can someone help me understand how to implement getStaticPaths in conjunction with Redux in Next.js? I'm currently using next-redux-wrapper to manage my content, but I am encountering issues when trying to display the data. Below is a snippet of my ...

Flask is failing to display AJAX data

Looking to embark on a Flask project involving sending an AJAX request. In the Flask code, I want to assign a variable to handle the request and display it on the page using a Jinja variable. Flask from flask import Flask,render_template,request app = Fla ...