Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

244
Visualizações
VueJS v-for loop, detect if previous element in object was different? (Change cities, etc)

This is a tough one... I have an array like


[{'city':'LA','store':'Bobs Burgers'},{'city':'LA','store':'Burger King'},{'city':'Sacramento','store':'Jimmy Burger'}]

If I am looping through these burger places in a table and I want to add in a row when the city changes, how do I do that?

In PHP I would do


<?php
foreach ($store in $burgerplaces){

if ($store['city']!=$prev_city){
   # show header for the city 
}

#print store info

$prev_city=$store['city'];

}
?>
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

If i understood you correctly try like following snippet (in computed property first sort your array then loop, compare cities and add empty object before next city):

new Vue({
  el: "#demo",
  data() {
    return {
      burgers: [{'city':'LA','store':'Bobs Burgers'},{'city':'Sacramento','store':'Jimmy Burger'},{'city':'LA','store':'Burger King'}, {'city':'NY','store':'Burgers'}]
    }
  },
  computed: {
    byCities() {
      const arr = this.burgers.sort((a,b) => {
        const nameA = a.city.toUpperCase();
        const nameB = b.city.toUpperCase(); 
        if (nameA < nameB) {
          return -1;
        }
        if (nameA > nameB) {
          return 1;
        }
        return 0;
      })
      const res = []
      for(let i = 0; i < arr.length; i++){
        if (i ===0 || arr[i].city !== arr[i-1].city) {
          res.push({city: arr[i].city.toUpperCase()})
        }
        res.push(arr[i])
      }
      return res
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <li v-for="(burger, i) in byCities" :key="i">
    {{ burger.city }}  {{ burger.store }}
  </li>
</div>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda