Home > Software design >  How can you convert a List<Pair<String,String>> to List<String> in javascript?
How can you convert a List<Pair<String,String>> to List<String> in javascript?

Time:04-22

This is the Output: The data structure for the output is Map<String, List<Pair<String, String>>>

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

Now I need to display this data on the UI as "testdata":["1.0","1.1","1.2"], wherein here from the Pair, I want to fetch only the first elements from the Pair and put them in the structure Map<String, List<String>>

So how do I write that code in javascript in order to get that output?

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

How do I modify this code to get this output "testdata":["1.0","1.1","1.2"]?

CodePudding user response:

You could try something like this:


// This assumes that there will be only one key in each array item, or the first key in each array item denotes the version

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

// or as MikeT suggested, if you are only expecting something like this:
// [
//  { "v1": "some value 1" },
//  { "v2": "some value 2" },
//  ... in general --> { "version": "some value" }
// ]
// you may try this as well
this.previousData = 
    versions
     .filter(v => v !== this.version)
     .map(item => Object.keys(item))
     .flat()


CodePudding user response:

your question isn't too clear about which element you are struggling with

so to get the data

async getData()
{
    const resp = await fetch("<<your url from your java service>>" )
    return await resp.json();
}

to format the data as you wish it to be formatted

formatData(json){
    return json.testdata.map((i)=>Object.entries(i).map(([k,v])=>k)).flat()
}

and to display in vue

<template>testdata:{{testdata}}</template>
<script>
...
     methods:{
        async populatedata(){
            const tmp = await getData()
            this.testdata = formatData(tmp)
        }
     }
...
</script>

Object.entries will convert an object into a tuple array so {"1.0":"True","1.1":"False"} will become [["1.0","True"],["1.1":"False"]] which then lets you use tuple decomposition to get the keys

you could also use Object.keys() if you have no need for the values but that wasn't clear from the context so i gave you the more flexible option

  • Related