How can you use JavaScript to iterate through an Array of Objects and create a new Object that combines arrays based on a specific key?

How can JavaScript iterate through an Array of Objects and return a new Object with merged arrays based on Object keys?

The original Array of Objects is as follows:

this.obj = [
    {
        "name": "test name 1",
        "teams": [{
            "manage": false,
            "name": "my test team",
        }]
    },
    {
        "name": "test name 2",
        "teams": [{
            "manage": false,
            "name": "TEAM2",
        }]
    }
];

The expected result should be:

{
    "teams": [{
        "manage": true,
        "name": "TEAM2",
    }, {
        "manage": false,
        "name": "my test team",
    }]
}

I was able to achieve this using two nested loops and a variable. How can this scenario be approached in JavaScript in a more efficient way?

let data = {'teams': []};

for (var i = this.obj.length - 1; i >= 0; i--) {
  for (var p = this.obj[i].teams.length - 1; p >= 0; p--) {
     data.teams.push(this.groups[i].teams[p]);
  }
}

Answer №1

One way to obtain an object as the result is by utilizing the `reduce()` function.

var items = [{"name":"example name 1","teams":[{"manage":false,"name":"my example team"}]},{"name":"example name 2","teams":[{"manage":false,"name":"TEAM3"}]}];

var outcome = items.reduce(function(res, elem) {
  res.teams = (res.teams || []).concat(elem.teams)
  return res
}, {})

console.log(outcome)

Answer №2

One way to achieve this is by iterating through the array and then looping through the keys of the object. If a key does not match 'name', you can add its content to the result array with the same key.

var data = [{ "name": "test name 1", "teams": [{ "manage": false, "name": "my test team", }] }, { "name": "test name 2", "teams": [{ "manage": false, "name": "TEAM2", }] }],
    result = {};

data.forEach(function (o) {
    Object.keys(o).forEach(function (k) {
        if (k !== 'name') {
            result[k] = (result[k] || []).concat(o[k]);
        }
    });
});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №3

In this particular situation, my recommendation would be to utilize the Map method when working with arrays.

var data = [{ "name": "example name 1", "teams": [{ "manage": false, "name": "team A", }] }, { "name": "example name 2", "teams": [{ "manage": false, "name": "TEAM B", }] }],
result = {};

data.map(function(obj){
result.teams = (result.teams || []).concat(obj.teams)
});
console.log(result);

Alternatively, you could consider using the reduce method for a more streamlined solution. This method serves a different purpose and can be helpful in various scenarios. For further information, refer to https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

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

Shifting the div with a sliding animation!

My webpage features a video background with text overlay, and I am looking to add a button in the center of the page. When users click on this button, I want the current text div to slide up using a CSS transition, revealing another div with the same effec ...

Creating a unique Angular 2 Custom Pipe tutorial

I've come across various instances of NG2 pipes online and decided to create one myself recently: @Pipe({name: 'planDatePipe'}) export class PlanDatePipe implements PipeTransform { transform(value: string): string { return sessionStor ...

Looping through JSON keys using ng-repeat in AngularJS

I am currently working on a project where I need to populate some JSON data retrieved from the Google Tag Manager API and then send this information to the frontend which is developed in AngularJS. At the moment, I am utilizing ng-repeat on a card compone ...

In order to utilize the componentDidUpdate lifecycle method, I passed props to the Outlet component while nesting it

I am currently using react-router-v6 and encountering some issues with my configuration. I have implemented nested routing with layouts according to the following settings. App.js <BrowserRouter> <Routes> <Route exact pat ...

Version 1 of Vue.js is not compatible with Ajax-loaded HTML files

Currently, I am encountering a minor issue with loading content through ajax requests. I am in the process of developing a web application where everything is located on one page without any reloading. To achieve this, I have split the content into separa ...

Guide on transferring LatLng ArrayList to a different LatLng ArrayList

I am working with 2 sets of latitude and longitude coordinates. List<LatLng> FirstSet = new ArrayList<LatLng>(); List<LatLng> SecondSet = new ArrayList<LatLng>(); Adding Coordinates to FirstSet FirstSet.add(pLatLng); At some poi ...

PlaneGeometry at x=0 y=0 z=0 for three.js on a flat surface

Hi there! I have a code snippet that currently renders an image vertically, and I'm looking to modify it so that the PlaneGeometry is drawn horizontally instead. Rather than rotating it with mesh.rotation.x=THREE.Math.degToRad(-90);, I'd like it ...

Retrieving weather data in JSON format from the Open Weather Map API

Recently, I've been delving into learning Angular for my own personal growth. To aid in this journey, I've been diligently following tutorials on CodeAcademy and PluralSight, specifically focusing on the AngularJS: Get Started stream. While enco ...

Retrieving data from a newly inserted document using Node JS and Mongoose

I've encountered a dilemma with my code: var newresult = "" oneDoc = { "adClientID": *randomID*, "adClientName": "abc", "adClientNameUPC": "ABC" } newdoc.push(oneDoc) await AdClient.create( ...

kineticjs equivalent to jquery sortable

Could someone recommend a kineticjs plugin or script that works with jquery's "sortable" function? I am trying to create a list of shapes where I can drag and drop them, and when one element moves, the other elements shift into place. ...

Header Express does not contain any cookies, which may vary based on the specific path

In my express.js app, I have two controllers set up for handling requests: /auth and /posts. I've implemented token authorization to set the Authorization cookie, but I'm encountering an issue when making a request to /posts. The request goes th ...

What methods can be used to configure Jasmine to read individual Vue component files?

I recently installed Jasmine and Vue through npm, but I'm encountering an issue when trying to import the Vue component itself, which is a .vue file. It seems to be having trouble reading the template section enclosed within <template></templ ...

What is the best way to identify which JavaScript code is triggering or managing an event?

In the development of an HTML5 application framework designed for businesses to use on their intranet and extranet sites, a SAP JEE application server is utilized. The framework incorporates the grid system known as "Semantic UI" along with various JavaScr ...

How can we incorporate dynamic HTML elements into a React JS application?

My code seems to be having an issue. I'm working on a registration form and trying to include an error message if the passwords entered do not match. For some reason, I am unable to dynamically add a para tag to my HTML. Any insights on why this could ...

How to visually deactivate a flat button ( <input type="button"> ) programmatically with JavaScript

I am facing an issue with my buttons. I have one regular button and another flat button created using input elements. After every click, I want to disable the buttons for 5 seconds. The disable function is working properly for the normal button, but for th ...

You are only able to click the button once per day

I am working on a button that contains numeric values and updates a total number displayed on the page when clicked. I would like this button to only be clickable once per day, so that users cannot click it multiple times within a 24 hour period. Below i ...

What is the best way to import API Endpoints from various directories in an Express Server?

I have been using a script to load my API endpoints like this: readdirSync('./routes/api').map((r) => app.use( `/api/v1/${r.split('.')[0]}`, require(`./routes/api/${r.split('.')[0]}`) ) ); This script reads eve ...

I keep encountering the following issue: "It seems that the file requested at /images/crown.png is not recognized as a valid image, as it was received as text/html; charset=utf-8."

I encountered an issue while utilizing Next.js. Here is the code snippet where the error occurred: import React from "react"; import { Container, Col, Row } from "react-bootstrap"; import Image from "next/image"; export defaul ...

Generate a custom website using React to display multiple copies of a single item dynamically

As a newcomer to React and web development, I've been pondering the possibility of creating dynamic webpages. Let's say I have a .json file containing information about various soccer leagues, structured like this: "api": { "results": 1376, ...

Unable to retrieve jwt token from cookies

Currently, I am developing a website using the MERN stack and implementing JWT for authentication. My goal is to store JWT tokens in cookies. Despite invoking the res.cookie function with specified parameters (refer to the code below), I am facing difficul ...