arrays - Turning a plain text string into a table using Javascript -
i'm scratching head around javascript exercise: receive plain text using ajax:
“201 george / / ” “301 mary / 302 lucy / ” “401 craig da / 402 ann / 403 al mia”
i need create 3 objects this:
{ "floor2": [{ "apart": "201", "name": "george" }], "floor3": [{ "apart": "301", "name": "mary" }, { "apart": "302", "name": "lucy" }], "floor4": [{ "apart": "401", "name": "craig d" }, { "apart": "402", "name": "ann" }, { "apart": "403", "name": "al mia" }] }
the table below visual aid.
apartment 1 | name | apartment 2 | name | apartment 3 | name -------------------------------------------------------------------------------- 201 | george | - | - | - | - -------------------------------------------------------------------------------- 301 | mary | 302 | lucy | - | - -------------------------------------------------------------------------------- 401 | craig d | 402 | ann | 403 | al mia
i have long code lots of arrays within arrays, think can done in cleaner way.
i quite fond of reduce. should going. have assumed floor can derived position in data there not seem better source.
var text = "\"201 george / / \"\n\"301 mary / 302 lucy / \"\n\"401 craig da / 402 ann / 403 al mia\""; var floors = text.split("\n"); var buildingdata = floors.reduce(function(flooracc, floor, floorindex){ // rid of odd quotes. floor = floor.slice(1, -1); var units = floor.split("/"); flooracc["floor" + (floorindex + 2)] = units.reduce(function(unitacc, unit){ var parts = unit.trim().split(" "); if (parts[0].trim() === ""){ return unitacc; } unitacc.push({"apartment" : parts[0], "name" : parts.slice(1).join(" ")}); return unitacc; }, []); return flooracc; }, {}); console.log(buildingdata);
Comments
Post a Comment