Я бы использовал конструктор или класс. Я предпочитаю конструкторов из-за их способности поддерживать частные переменные с меньшим количеством работы (не показано в примере) . Проверьте это!
function Theaterminal(dataArray){
this.states = [];
this.getPlace = (state, city)=>{
let sx = new RegExp('^'+state+'$', 'i'), cx;
if(city)cx = new RegExp('^'+city+'$', 'i');
for(let s of this.states){
if(s.state.match(sx)){
if(city){
for(let c of s.cities){
if(c.city.match(cx)){
return c;
}
}
return false;
}
else{
return s;
}
}
}
return false;
}
this.parse = data=>{
let s = this.states, w, q, t, c, b;
s.splice(0);
data.forEach(o=>{
w = o.state; q = this.getPlace(w); t = {id:o.theatreId, desc:o.theatreDescription}; c = {city:o.city, theaters:[t]};
if(q === false){
s.push({state:w, cities:[c]});
}
else{
b = this.getPlace(w, o.city);
if(b === false){
q.cities.push(c);
}
else{
b.theaters.push(t);
}
}
});
return s;
}
this.parse(dataArray);
}
const data = [
{
city: 'LAKE GENEVA',
state: 'WISCONSIN',
theatreId: '000080',
theatreDescription: 'GENEVA 4'
},
{
city: 'BURLINGTON',
state: 'WISCONSIN',
theatreId: 'c05364',
theatreDescription: 'PLAZA THEATRE 4'
},
{
city: 'LAKE GENEVA',
state: 'WISCONSIN',
theatreId: 'fakeId',
theatreDescription: 'fake theater'
},
{
city: 'SEATTLE',
state: 'WASHINGTON',
theatreId: 'example id',
theatreDescription: 'why bother'
}
];
const terminal = new Theaterminal(data);
console.log(terminal.states);
console.log('-----------------------check this out--------------------');
console.log(terminal.getPlace('wisconsin', 'lake geneva'));
Обратите внимание, что если вы передадите dataArray
в TheaterminalInstance.parse(here)
, TheaterminalInstance.states
также изменится, не потеряв свою ссылку на объект. dataArray
не будет изменено.