Iterate through the array and combine elements that have identical key/value pairs

I have an array of objects:

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

I am iterating over the array using the following loop:

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

This setup results in:

<div>
    <h5>age: 5</h5>
    <ul>
        <li>foo</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>

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

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

I'm considering creating a separate object and combining the contents of arrays if the age key/value pairs match. How can I achieve this?

Answer №1

Here is a code snippet that you can try:

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="app">
   <div v-for="(arr, index) in newArr" :key="index">
    <h5>Age Group: {{ arr.age }}</h5>
    <ul>
        <li v-for="(name, i) in arr.name" :key="i">{{ name }}</li>
    </ul>
</div>
</div>

Answer №2

If you want to customize the appearance of your object, you can manipulate it before creating a 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("==========================");
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Vue API and Frame

Just starting out. Looking to display a skeleton while waiting for data from the API. Any ideas on how to achieve this? Appreciate any help My workaround involved implementing a timeout function ...

Is it possible to confirm jQuery AJAX events using Jasmine?

I'm currently working on using Jasmine to write BDD specifications for basic jQuery AJAX requests. I've set up Jasmine in standalone mode through SpecRunner.html and configured it to load jQuery and other necessary .js files. However, I'm fa ...

Designing a file upload progress bar with the help of jquery and ajax

I am looking to implement a progress bar for uploading files utilizing jquery and ajax. Here is the jquery code I have written: function updateProgress(evt) { // evt is an ProgressEvent. if (evt.lengthComputable) { var percentLoaded = ...

Guide on building a Vue Js input name field with string-variable schema

I have a project using VueJs and I am looking to extract JavaScript variables to create hidden fields. My goal is to set the name of the field based on the index of the variable, following a zig-zag naming schema. For example: <input type="text" nam ...

Coding with a combination of JavaScript, AngularJS, and manipulating brackets

I am currently performing the following action: myArray.push(pageCount); After that, I end up with something like this: $scope.myArray = Pages.getAllPageCount(); Finally, when I utilize AngularJS to display it in my .html file. {{myArray}} If there i ...

The type 'Observable<Object>' cannot be assigned to type 'Observable<IUser[]>'

My Api service contains a simple function called getUsers, which is used to fetch all the users on the api. public getUsers(url: string): Observable<IUser[]> { return this._http.get(url); } The IUser interface I have created has all fields marke ...

What is the best way to maintain the previous input value on page refresh in Vuejs?

In my development project, I am utilizing the Laravel and Vue.js technologies. I am facing an issue where I need to set the input value to its previous old value when either refreshing the page or navigating back to it in a Vue dynamic component. Here is ...

What is the procedure for obtaining a list of items with the second item marked as "true"?

Can you please provide guidance on how to iterate through a list of addresses (address object) where the object has the property "def" set to true? Here is an example response from an API request: { "status": true, "rspa": ...

How to handle type errors when using properties in Vue3 Single File Components with TypeScript

I've hit a roadblock while attempting to utilize properties in Vue3. Despite trying various methods, I keep facing issues during the type-check phase (e.g.: yarn build). The project I'm working on is a fresh Vue3-ts project created using Vite. B ...

How can we identify if a React component is stateless/functional?

Two types of components exist in my React project: functional/stateless and those inherited from React.Component: const Component1 = () => (<span>Hello</span>) class Component2 extends React.Component { render() { return (<span> ...

Top method for obtaining base64 encoding of an image in Angular or Node.js

Looking to obtain Base64 data for images. Currently utilizing Angular 6 on the frontend and NodeJS on the backend. Should I extract the Base64 string on the frontend or is it better to handle conversion on the backend before returning it to the frontend? ...

Edit: "Submit a binary file with just JavaScript"

I am currently developing a Chrome application that utilizes the HTML5 Filesystem API to enable users to import and synchronize files. A challenge I'm facing is when attempting to sync image files, as they appear to become corrupted during the upload ...

What is the best way to attach an image to the image section coming from the backend in vue.js?

I have developed a frontend page that displays a list of books, with the data coming from the backend. The backend response includes image files, and I am struggling to bind these images to the image section of my template. I have the image paths from the ...

Differences between encoding URL variables in HREF and using JS window.location for onclick events

For some reason, this particular hyperlink is not functioning properly. I have a Javascript redirect (window.opener.location) where I pass several variables through the URL. The problem arises when these variables contain apostrophes. In PHP, I am using UR ...

Express/axios fails to properly configure cookies and headers for response delivery

I am facing a complex issue with my project that involves two APIs. One API serves as the front-end of the application, while the other is for the back-end. The process simply entails sending requests from the front-end API to the back-end API. The front- ...

Is there a way to prevent continuous repetition of JavaScript animated text?

I'm working on a code that displays letters and words one by one, but I can't figure out how to stop it from repeating. Can someone help me with this? <div id="changeText"></div> <script type="text/javascript"> var te ...

Tips for avoiding an automatic slide up in a CSS menu

Is there a way to disable the automatic slide-up effect on my CSS menu when clicking a list item? I have tried using stop().slideup() function in my JavaScript code, but it doesn't seem to work. Additionally, I would like to highlight the selected lis ...

Using arrays to pass parameters in JavaScript

I have multiple sliders that require the same set of parameters to be passed to each one. My understanding is that I need to use an array for this purpose. However, as a JavaScript novice, I am unsure of the correct way to implement it. The parameters lo ...

Issues with the pushState feature on the Angular platformLocation

When the platform is loaded for the first time, I want to inject a new state into the browser history so that when the user clicks the back button, they are taken to the home page of the app. I have attempted to add a new state using: 1. PlatformLocation ...

Modifying the style of the HTML placeholder tag

One approach I am taking involves utilizing a placeholder element within my search box input: <input id="searchBarTextbox" type="search" class="k-textbox" placeholder="Search For..." /> My challenge now is to enhance the aesthetics of the placehold ...