Search code examples
javascriptarraysstringify

Convert multidimensional Array to specific String format


I receive an array that I must convert into a specific string format.

This is the array:

formdata: [
    1: {name: "gender", value: "F", focus: 0, type: "radio"}
    2: {name: "firstname", value: "empty", focus: 0, type: "input"}
    3: {name: "lastname", value: "empty", focus: 0, type: "input"}
    4: {name: "birthday", value: "empty", focus: 0, type: "input"}
    5: {name: "street", value: "empty", focus: 0, type: "input"}
    6: {name: "streetNo", value: "empty", focus: 0, type: "input"}
]

And this is the specific string format it should be converted to:

let formdata = gender.radio|F|0;firstName.text|empty|1;lastName.text|empty|0;street.text|empty|0;houseNumber.text|empty|0;zip.text|empty|0;city.text|empty|0;country.select-one|de|0;birthdate-day.text|empty|0;birthdate-month.text|empty|0;birthdate-year.text|empty|0;email.email|empty|0;code.text|filled_out|0

I assume it is best to use JSON.stringify. I have tried several variations along the lines of this:

let formdata = JSON.stringify(
formdata: [
    1: {name: "gender", value: "F", focus: 0, type: "radio"}
    2: {name: "firstname", value: "empty", focus: 0, type: "text"}
    3: {name: "lastname", value: "empty", focus: 0, type: "text"}
    4: {name: "birthday", value: "empty", focus: 0, type: "text"}
    5: {name: "street", value: "empty", focus: 0, type: "text"}
    6: {name: "streetNo", value: "empty", focus: 0, type: "text"}
])
.replace(/(\]\]\,)\[/g, "]\n")..replace(/(\[\[|\]\]|\")/g,"");

None of them worked.

Any ideas how to solve this?

Thanks!


Solution

  • I think just use map() on the array. And return Template String. And then join() array by ';'

    const formdata = [
        {name: "gender", value: "F", focus: 0, type: "radio"},
        {name: "firstname", value: "empty", focus: 0, type: "input"},
        {name: "lastname", value: "empty", focus: 0, type: "input"},
        {name: "birthday", value: "empty", focus: 0, type: "input"},
        {name: "street", value: "empty", focus: 0, type: "input"},
        {name: "streetNo", value: "empty", focus: 0, type: "input"},
    ]
    
    
    let res = formdata.map(({name,value,focus,type}) => `${name}.${type}|${value}|${focus}`).join(';')
    
    console.log(res)