Итерация по массиву объектов и формирование нового - PullRequest
0 голосов
/ 31 марта 2020

Я пытаюсь перебрать массив объектов ниже

var data = [
  {
    city: 'LAKE GENEVA',
    state: 'WISCONSIN',
    theatreId: '000080',
    theatreDescription: 'GENEVA 4'
  },
  {
    city: 'BURLINGTON',
    state: 'WISCONSIN',
    theatreId: 'c05364',
    theatreDescription: 'PLAZA THEATRE 4'
  }
]

Мне нужно, чтобы он был преобразован в нечто вроде ниже

[{
        "state": "WISCONSIN",
        "city": [
        {
            "desc": "LAKE GENEVA",
            "theatres": [{
                    "id": "000080",
                    "desc": "GENEVA 4"
                }]
        }, 
        {
            "desc": "BURLINGTON",
            "theatres": [{
                    "id": "c05364",
                    "desc": "PLAZA THEATRE 4"
                }]
        }
    ]

}]

Есть ли способ, которым я мог бы сделать это используя HashMap?

Ответы [ 3 ]

1 голос
/ 31 марта 2020

Вам необходимо сгруппировать объект массива, используя Array.prototype.reduce на основе свойства state, затем проверьте, существует город или нет, если он существует, перезаписать с последними значениями, иначе pu sh это в массив city, также вам нужно проверить театр, в конце вам нужно вернуть аккумулятор для следующей итерации.

const data1 = [{
    city: 'LAKE GENEVA',
    state: 'WISCONSIN',
    theatreId: '000080',
    theatreDescription: 'GENEVA 4'
  },
  {
    city: 'BURLINGTON',
    state: 'WISCONSIN',
    theatreId: 'c05364',
    theatreDescription: 'PLAZA THEATRE 4'
  }
];

const data2 = [{
  city: 'MIAMI',
  state: 'FLORIDA',
  theatreId: 'c05170',
  theatreDescription: 'DOLPHIN 24'
}, {
  city: 'MIAMI',
  state: 'FLORIDA',
  theatreId: '000306',
  theatreDescription: 'CMX BRICKELL CITY CENTRE 10'
}];

const reduceCityTheaters = (arr) => Object.values(arr.reduce((acc, curr) => {
  // Deconstruct needed properties
  const { state, city, theatreId, theatreDescription } = curr;
  
  // Check if state not present
  if (!acc[state]) {
    let obj = {};
    obj.state = state;
    obj.city = [{
      desc: city,
      theatres: [{
        id: theatreId,
        desc: theatreDescription
      }]
    }];

    acc[state] = obj;
  } else { // Check if state is present
    acc[state].city = acc[state].city || [];
    const foundCity = acc[state].city.find(x => x.desc === city);

    // Check if city exists or not if not push it
    if (!foundCity) {
      acc[state].city.push({
        desc: city,
        theatres: [{
          id: theatreId,
          desc: theatreDescription
        }]
      });
    } else {
      const foundTheater = foundCity.theatres.find(x => x.id === theatreId);

      // Check if theatre exists or not if not push it
      if (!foundTheater) {
        foundCity.theatres.push({
          id: theatreId,
          desc: theatreDescription
        });
      } else {
        foundTheater.id = theatreId;
        foundTheater.desc = theatreDescription;
      }
    }
  }

  return acc;
}, {}));


const res1 = reduceCityTheaters(data1);
const res2 = reduceCityTheaters(data2);

console.log('1', res1);
console.log('2', res2);
0 голосов
/ 31 марта 2020

Я бы использовал конструктор или класс. Я предпочитаю конструкторов из-за их способности поддерживать частные переменные с меньшим количеством работы (не показано в примере) . Проверьте это!

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 не будет изменено.

0 голосов
/ 31 марта 2020

попробуйте

var data = [
  {
    city: 'LAKE GENEVA',
    state: 'WISCONSIN',
    theatreId: '000080',
    theatreDescription: 'GENEVA 4'
  },
  {
    city: 'BURLINGTON',
    state: 'WISCONSIN',
    theatreId: 'c05364',
    theatreDescription: 'PLAZA THEATRE 4'
  }
]

let group = data.reduce((r, a) => {
 r[a.state] = [...r[a.state] || [], a];
 return r;
}, {});

let nowObj ={};
for (let [key, value] of Object.entries(group)) {
  let groupNew = value.reduce((r, a) => {
      r[a.city] = [...r[a.city] || [], a];
      return r;
  }, {});
  nowObj[key] =groupNew;
}
let mainObj=[];
for (let [key, value] of Object.entries(nowObj)) {
  let obj ={};
  let city =[];
  for (let [key2, value2] of Object.entries(value)) {
    let cityObj ={};
    cityObj['desc'] =key2;
    cityObj['theatres'] =value2.map(item => {
      const container = {};
      container['id'] = item.theatreId;
      container['des'] = item.theatreDescription;
      return container;
    });
    city.push(cityObj);
  }
  obj['state'] =key;
  obj['city'] =city;
  mainObj.push(obj);
}

console.log(mainObj);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...