settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: Towns to JSON - JavaScript task

+2 votes

You’re tasked to create and print a JSON from a text table. You will receive input as an array of strings, where each string represents a row of a table, with values on the row encompassed by pipes "|" and optionally spaces. The table will consist of exactly 3 columns “Town”, “Latitude” and “Longitude”. The latitude and longitude columns will always contain valid numbers. Check the examples to get a better understanding of your task.

The input comes as an array of strings – the first string contains the table’s headings, each next string is a row from the table.

Examples:

Input:
['| Town | Latitude | Longitude |',
'| Sofia | 42.696552 | 23.32601 |',
'| Beijing | 39.913818 | 116.363625 |']

Output:
[{"Town":"Sofia","Latitude":42.69,"Longitude":23.32},
{"Town":"Beijing","Latitude":39.91,"Longitude":116.36}]


Input:
['| Town | Latitude | Longitude |',
'| Veliko Turnovo | 43.0757 | 25.6172 |',
'| Monatevideo | 34.50 | 56.11 |']

Output:
[{"Town":"Veliko Turnovo","Latitude":43.0757,"Longitude":25.6172},
{"Town":"Monatevideo","Latitude":34.5,"Longitude":56.11}]


The output should be printed on the console – for each entry row in the input print the object representing it.

asked in JavaScript category by user ak47seo

1 Answer

+1 vote

Here is the code:

function townsToJSON(towns) {

    let townsArr = [];
    for (let town of towns.slice(1)) {//ignore the first element of the array
        let [empty,townName,lat,lng]=town.split(/\s*\|\s*/);
        let townObj = {
            Town: townName,
            Latitude: Number(lat),
            Longitude: Number(lng)
        };
        townsArr.push(townObj);//adds elements to the array
    }
    console.log(JSON.stringify(townsArr));
}

townsToJSON(['| Town | Latitude | Longitude |',
        '| Sofia | 42.696552 | 23.32601 |',
        '| Beijing | 39.913818 | 116.363625 |']
);

 

answered by user andrew
...