我对这个javascript练习摸不着头脑:我使用Ajax接收这个纯文本:
“201 George / / ”
“301 Mary / 302 Lucy / ”
“401 Craig Da / 402 Ann / 403 Al Mia”
我需要像这样创建3个对象:
{
"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"
}]
}
下面的表格只是一个直观的帮助。
Apartment 1 | Name | Apartment 2 | Name | Apartment 3 | Name
--------------------------------------------------------------------------------
201 | George | - | - | - | -
--------------------------------------------------------------------------------
301 | Mary | 302 | Lucy | - | -
--------------------------------------------------------------------------------
401 | Craig D | 402 | Ann | 403 | Al Mia
我有一个很长的代码,有很多数组中的数组,但我认为它可以在一个更干净的方式。
我很喜欢reduce。这应该能让你继续。我假设地板可以从数据中的位置导出,因为似乎没有更好的来源。
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){
// get rid of the 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);
在ES6中的另一个例子
function customTransform(text) {
const myData = {};
const props = ['apart', 'name'];
const rx = /“([sS]+?)”/g;
let match = rx.exec(text);
while (match) {
const tenants = match.pop().split('/').map(m => m.trim()).filter(Boolean);
if (tenants.length) {
let floor = tenants[0].charAt(0);
if (/^d$/.test(floor)) {
floor = `floor${floor}`;
myData[floor] = [];
for (let tenant of tenants) {
tenant = tenant.match(/^(d{3})s*([sS]*)$/);
if (tenant) {
tenant.shift();
myData[floor].push(props.reduce((p, x) => {
p[x] = tenant.shift();
return p;
}, {}));
}
}
myData[floor].sort((a, b) => a.apart.localeCompare(b.apart));
}
}
match = rx.exec(text);
}
return myData;
}
let text = '“201 George / / ”
“301 Mary / 302 Lucy / ”
“401 Craig Da / 402 Ann / 403 Al Mia”';
console.log(customTransform(text));
text = '“ / 202 George / ”
“ / 302 Mary / 303 Lucy ”
“402 Craig Da / 403 Ann / 401 Al Mia”';
console.log(customTransform(text));
text = '“201 George / / ”n“301 Mary / 302 Lucy / ”n“401 Craig Da / 402 Ann / 403 Al Mia”';
console.log(customTransform(text));