Home > Back-end >  Loop over array and merge elements with same key/value pair
Loop over array and merge elements with same key/value pair

Time:10-22

I've got an array of objects:

array = [
    {
        age: 5,
        name: foo
    },
    {
        age: 5,
        name: bar
    },
    {
        age: 8,
        name: baz
    }
]

I loop over the array like this:

<div v-for="(arr, index) in array" :key="index">
    <h5>age: {{ arr.age }}</h5>
    <ul>
        <li>{{ arr.name }}</li>
    </ul>
</div>

which renders like this:

<div>
    <h5>age: 5</h5>
    <ul>
        <li>foe</li>
    </ul>
</div>
<div>
    <h5>age: 5</h5>
    <ul>
        <li>bar</li>
    </ul>
</div>
<div>
    <h5>age: 8</h5>
    <ul>
        <li>baz</li>
    </ul>
</div>

however I want the arrays with the same age to merge like this:

<div>
    <h5>age: 5</h5>
    <ul>
        <li>foe</li>
        <li>bar</li>
    </ul>
</div>
<div>
    <h5>age: 8</h5>
    <ul>
        <li>baz</li>
    </ul>
</div>

I'm thinking about making a separate object and merging the content of the arrays if the age key/value pairs are the same. How can I obtain this?

CodePudding user response:

You can parse your object to build an object that looks how you like and then build your template

array = [
  {
    age: 5,
    name: "foo"
  },
  {
    age: 5,
    name: "bar"
  },
  {
    age: 8,
    name: "baz"
  }
];
var newarr = {};
array.map((e) => {
  if (!newarr[e.age]) newarr[e.age] = [];
  newarr[e.age].push(e.name);
});

for (const [key, value] of Object.entries(newarr)) {
  console.log(`${key}`);
  for (const v of value) {
  console.log(`${v}`);
  }
  console.log("==========================");
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Try like following snippet:

new Vue({
  el: '#demo',
  data() {
    return {
      array: [{age: 5, name: 'foo'}, {age: 5, name: 'bar'}, {age: 8, name: 'baz'}]
    }
  },
  computed: {
    newArr() {
      const uniques = [...new Set(
      this.array.map(x => JSON.stringify(((o) => ({
            age: o.age,
        }))(x))))
      ].map(JSON.parse);
      this.array.forEach(a => {
          let idx = uniques.findIndex(u => u.age === a.age)
          if(!uniques[idx].name) uniques[idx].name = []
          uniques[idx].name.push(a.name)
      })
      return uniques
    }
  }
})

Vue.config.productionTip = false
Vue.config.devtools = false
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
   <div v-for="(arr, index) in newArr" :key="index">
    <h5>age: {{ arr.age }}</h5>
    <ul>
        <li v-for="(name, i) in arr.name" :key="i">{{ name }}</li>
    </ul>
</div>
</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related