Невозможно отобразить все объекты в массиве в цикле v-for, отображается только последний объект

Я ввожу некоторые данные. Я группирую эти данные по ключу, а затем пытаюсь распечатать их в цикле v-for в Vue.

Код выглядит примерно так:

// I initialize an empty array in data
data() {
  return {
    locArray: []
  }
}


// This is done in the api call, in beforeRouteEnter()

const items = data.continental;

Array.prototype.groupBy = function(prop) {
  return this.reduce(function(groups, item) {
    const val = item[prop];
    groups[val] = groups[val] || [];
    groups[val].push(item);
    return groups;
  }, {});
};

for (let i in items) {
  let source = items[i];
  let details = source.details;
  let groupedByLocation = details.groupBy(location);
  vm.locArray = groupedByLocation
}

// This is an example of what the data looks like
{
  data: {
    continental: {
      countryOne: {
        weather: "weatherOne",
        details: [{
          location: "west",
          foods: "foodOne",
          mainCities: [
            "cityOne",
            "cityTwo",
            "cityThree"
          ]
        }]
      },
      countryTwo: {
        weather: "weatherTwo",
        details: [{
          location: "north",
          foods: "foodTwo",
          mainCities: [
            "cityOne",
            "cityTwo",
            "cityThree"
          ]
        }]
      },
      countryThree: {
        weather: "weatherThree",
        details: [{
          location: "north",
          foods: "foodThree",
          mainCities: [
            "cityOne",
            "cityTwo",
            "cityThree"
          ]
        }]
      },
      countryFour: {
        weather: "WeatherFour",
        details: [{
          location: "west",
          foods: "foodFour",
          mainCities: [
            "cityOne",
            "cityTwo",
            "cityThree"
          ]
        }]
      },
      countryfive: {
        weather: "WeatherFive",
        details: [{
          location: "north",
          foods: "foodFive",
          mainCities: [
            "cityOne",
            "cityTwo",
            "cityThree"
          ]
        }]
      }
    }
  }
}
<div class="entry-content">
  <div class="single-entry" v-for="loc in locArray" :key="loc.id">
    <span class="test-wrap">{{ loc }}</span>
  </div>
</div>

Когда я console.log(groupedByLocation) получаю все данные, которые должны отображаться, но в v-for я получаю только последний объект в массиве.

Это кажется простым, но я действительно в тупике.

Любая помощь будет оценена!

Желаемый результат заключается в том, что я хотел бы напечатать все элементы, которые имеют location: north вместе в группе выше, и все элементы, которые имеют location: west в другой группе ниже.


person ale_aalt    schedule 29.01.2019    source источник
comment
Можете ли вы поделиться каким-либо работающим примером, подобным jsFiddle (это будет большим подспорьем, чтобы выяснить проблему)?   -  person Sajib Khan    schedule 29.01.2019
comment
Ваше имя v-for="pos in posArray", а не v-for="pos in groupedByPos". Что в posArray?   -  person tao    schedule 29.01.2019
comment
@SajibKhan Я добавил дополнительные детали для ясности.   -  person ale_aalt    schedule 29.01.2019
comment
@AndreiGheorghiu Верно. Я добавил более подробный пример выше для ясности. То, что я вызываю в v-for (на этот раз locArray), получает содержимое groupedByLocation, что правильно распечатывается в console.log   -  person ale_aalt    schedule 29.01.2019
comment
Желаемый результат заключается в том, что я хотел бы напечатать все элементы, которые имеют location: north вместе в группе выше, и все элементы, которые имеют location: west в другой группе ниже.   -  person ale_aalt    schedule 29.01.2019


Ответы (1)


Я не понимаю, почему вы вызываете groupBy на каждой итерации цикла for.

Я бы решил эту фильтрацию с помощью details[0].location Object.values() с continental:

  methods: {
    filterByLocation: function(location) {
      return Object.values(this.continental).filter(v => v.details[0].location === location)
    }
  }

Пример:

new Vue({
  el: '#app',
  data: {
    continental: {
      countryOne: {
        weather: "weatherOne",
        details: [{
          location: "west",
          foods: "foodOne",
          mainCities: [
            "cityOne",
            "cityTwo",
            "cityThree"
          ]
        }]
      },
      countryTwo: {
        weather: "weatherTwo",
        details: [{
          location: "north",
          foods: "foodTwo",
          mainCities: [
            "cityOne",
            "cityTwo",
            "cityThree"
          ]
        }]
      },
      countryThree: {
        weather: "weatherThree",
        details: [{
          location: "north",
          foods: "foodThree",
          mainCities: [
            "cityOne",
            "cityTwo",
            "cityThree"
          ]
        }]
      },
      countryFour: {
        weather: "WeatherFour",
        details: [{
          location: "west",
          foods: "foodFour",
          mainCities: [
            "cityOne",
            "cityTwo",
            "cityThree"
          ]
        }]
      },
      countryfive: {
        weather: "WeatherFive",
        details: [{
          location: "north",
          foods: "foodFive",
          mainCities: [
            "cityOne",
            "cityTwo",
            "cityThree"
          ]
        }]
      }
    }
  },
  methods: {
    filterByLocation: function(location) {
      return Object.values(this.continental).filter(v => v.details[0].location === location)
    }
  }
})
#app {
  display: flex;
  justify-content: space-around;
  max-width: 600px;
  margin: 0 auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div>
    <h2>North locations</h2>
    <ol>
      <li v-for="loc in filterByLocation('north')" :key="loc.weather">
        {{loc.weather}}
      </li>
    </ol>
  </div>
  <div>
    <h2>West locations</h2>
    <ol>
      <li v-for="loc in filterByLocation('west')" :key="loc.weather">
        {{loc.weather}}
      </li>
    </ol>
  </div>
</div>

person tao    schedule 29.01.2019
comment
Это сработало как шарм! Думаю, я слишком усложнял вещи. Большое спасибо! - person ale_aalt; 30.01.2019