Is JavaScript the go-to solution for rearranging a list of objects?

I have come across a data structure related question that I believe would be best addressed in this forum. Recently, I have been encountering the following issue frequently. I receive data from a service in the following format. It consists of an array of people and their corresponding pets.

owners = [
  {
    owner: 'anne',
    pets: ['ant', 'bat']
  },
  {
    owner: 'bill',
    pets: ['bat', 'cat']
  },
  {
    owner: 'cody',
    pets: ['cat', 'ant']
  }
];

However, I am interested in having an array of pets and the owners who possess them, as shown below:

pets = [
  {
    pet: 'ant',
    owners: ['anne', 'cody']
  },
  {
    pet: 'bat',
    owners: ['anne', 'bill']
  },
  {
    pet: 'cat',
    owners: ['bill', 'cody']
  }
];

Is there a tool available that can automatically transform my input array into an array of unique pet objects, where each object includes a property with an array of owners?

Alternatively, do I have to manually code this transformation?

Answer №1

To create a new array, consider utilizing a hash table and looping through all owners and their pets.

var owners = [{ owner: 'alice', pets: ['dog', 'cat'] }, { owner: 'bob', pets: ['cat', 'fish'] }, { owner: 'carol', pets: ['fish', 'dog'] }],
    pets = [];

owners.forEach(function (owner) {
    owner.pets.forEach(function (pet) {
        if (!this[pet]) {
            this[pet] = { pet: pet, owners: [] }
            pets.push(this[pet]);
        }
        this[pet].owners.push(owner.owner);
    }, this)
}, Object.create(null));

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

Answer №2

Check out this solution utilizing the Array.prototype.reduce method and a hash table - view the demonstration below:

var owners=[{owner:'anne',pets:['ant','bat']},{owner:'bill',pets:['bat','cat']},{owner:'cody',pets:['cat','ant']}];

var pets = owners.reduce(function(hash) {
  return function(p,c){
    c.pets.forEach(function(e){
      hash[e] = hash[e] || [];
      if(hash[e].length === 0)
        p.push({pet:e,owners:hash[e]});
      hash[e].push(c.owner);
    });
    return p;
  }
}(Object.create(null)), []);

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

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

What is the best way to transmit the server response information from a fetch API to the client?

After receiving a response with the expected results from an API call using fetch API and a json object, I am looking for ways to send these results to the client in order to display them on the interface. The server-side operation was conducted through th ...

include a button next to the input field

As you reduce the browser window size, you may notice a different layout designed specifically for iPhone. One question that arises is how to add a button next to the search text box dynamically using JavaScript. The issue at hand is that the text box is b ...

Extracting the value of an HTML element from a string variable in AngularJS

I am facing an issue with my application where the content of an HTML element is received as a template from the server. I am attempting to assign this template, which is essentially a string, and have the variables within the template linked to the contro ...

Avoiding page refresh while utilizing the ng5-slider component in Angular

I am currently working with an ng5-slider that has a customizable range from 0 to 1000. However, I have encountered an issue when adjusting the slider at the bottom of the page - it refreshes and automatically takes me back to the top of the page. I would ...

Exclude a specific link from a JQuery function

Check out this unique single page site that utilizes a waypoint script for navigation and highlighting nav items - The functionality works seamlessly, however, we are facing an issue where we need to modify a link to redirect to an external website. Unfor ...

In Android studio, when updating the nth element in an array within a custom adapter, the 0th element is unexpectedly being updated as well. Here are some

In the realm of array functions, I've noticed a curious behavior. When updating the nth element in an array using a custom adapter, not only does it update the specified position but it also moves the original value to the zero position. For example, ...

Instructions for correctly setting up the test-ai-classifier plugin with appium for selecting UI elements

Encountered an issue on Ubuntu 20.04. Referenced the steps provided at https://github.com/testdotai/appium-classifier-plugin Installed test-ai-classifier both under the appium path and globally using npm install -g test-ai-classifier Ensured no errors f ...

Two trigger functions in Angular animations are not functioning as expected

After updating to the latest version of Angular and starting a new project, I encountered an issue with using two trigger() functions for animations. When attempting to use both trigger() functions, the second one would not work. However, disabling the fir ...

The file upload process did not return a successful response for Ajax

Recently delved into the world of Ajax and encountered a perplexing issue. Here is the dilemma: I successfully upload a .csv file to the server. However, after the upload "success" in the ajax call fails to trigger a response. Neither does complete or er ...

Steps to refresh your nodejs project after making changes

As a newcomer to nodejs, I find myself constantly restarting the server every time I make changes to my HTML files or when using twig, jade, or ejs template engines. Does anyone have any suggestions on how to see these changes in the browser without having ...

For every multi-dimensional array within PHPExcel

Can anyone help me with looping through a multidimensional array in PHP Excel? Here is the code I am currently using: $objWorkSheet = $this->excel->createSheet(1); //Setting index when creating $colors = array( array("A1", "B1", "C1", " ...

Tips for converting each item within an array into its own separate element

https://i.sstatic.net/Dxj1W.pngI currently have an array of objects that I am utilizing to generate a table in Angular. The table is functioning properly and successfully displays the data. However, I now have a requirement to enable editing for each indiv ...

Issue with PHP form not saving data and correctly parsing output

I am facing an issue with my PHP page where it is supposed to grab responses from a form, insert the data into a table, and then display the response on the same page. I am using ajax to send form values without refreshing the page, but unfortunately, no i ...

Populating a HTML document with data retrieved from an AJAX request

I have a button that, when clicked, should display the values of a specific user. The code snippet for this functionality is as follows: HTML Button: <button onclick="return getUserDetails(<? echo $user['id']; ?>)" class="btn btn-xs bt ...

Implementing JavaScript: Grouping JSON Response by Date and Category in a Table

The API response provided below contains sample data. {"success":true,"transaction":[{"_id":"58efd5717ddda769f26793fc","transId":"Exp/04-17/17","trpId":"Trav/dfsd/04-17/12","tripId":"58efd4dc7ddda769f26793f8","userId":"58ac19eaec1e7e4628be6f01","expenseHe ...

Tips for refreshing the tawk.to widget when the language changes with the help of i18next

Utilizing i18n-jquery for language switching and integrating the tawk.to chat widget, I've successfully loaded different languages on page reload. However, due to i18n not refreshing the page (which I don't want to do), I need to figure out how t ...

PHP - Retrieve fully rendered HTML content from an external page

I am a beginner when it comes to AJAX and PHP, and I have been experimenting with using a PHP HTML DOM Parser to retrieve the HTML from an external website. However, I have encountered an issue where the fetched HTML is only the content that was initially ...

I am looking to define values for an array in one node.js process and then retrieve it in another process

main.js var sendTickets = [] code1.js for(i=0;i<100;i++){ sendTickets.push(i); } code2.js sendTickets.forEach(function(element){console.log(element);}) In main.js, I declared an array variable named sendTickets. The elements of this array are populat ...

What is the process for dynamically incorporating JavaScript files during compilation to serve as input for browserify?

Within our project's structure, there exists a directory housing multiple js files. The possibility of adding or removing these files later on is present. Currently, we have a file named main.js where each file is imported and a map is created (using ...

Modifying script variables using the Chrome console

There is a button on the website that looks like this: https://i.sstatic.net/G7PBF.png Clicking on this button triggers the following script: https://i.sstatic.net/rIdLW.png function count(){ let downloadTimer; var timeleft = 30; downloadTimer = setInte ...