Is there a way to transform array and object into a new result in JavaScript by inverting them?

Embarking on a new project, I find myself in unfamiliar territory. The data at hand is structured as follows:

{
  domain1.com: [
    { city: "New-York" },
    { city: "Denver" },
    { city: "Las-Vegas" },
    { city: "Boston" },
  ]
},
{
  domain2.com: [
    { city: "Miami" },
    { city: "Las-Vegas" },
    { city: "Boston" },
  ]
},
{
  domain3.com: [
    { city: "New-York" },
    { city: "Miami" },
    { city: "Las-Vegas" },
    { city: "Chicago" },
  ]
}

The challenge now presents itself - can we restructure this data to form a list where each city is paired with its associated domain names? Consider the desired output below:

{
  New-York: [
    { domain: "domain1.com" },
    { domain: "domain3.com" },
  ]
},
{
  Denver: [
    { domain: "domain1.com" },
  ]
},
{
  Las-Vegas: [
    { domain: "domain1.com" },
    { domain: "domain2.com" },
    { domain: "domain3.com" },
  ]
},
{
  Boston: [
    { domain: "domain1.com" },
    { domain: "domain2.com" },
  ]
},
{
  Miami: [
    { domain: "domain2.com" },
    { domain: "domain3.com" },
  ]
},
{
  Chicago: [
    { domain: "domain3.com" },
  ]
},

Answer №1

Any additional comments would be appreciated. I devised this solution quickly

const data = [
  {
    "domain1.com": [
      { city: "New-York" },
      { city: "Denver" },
      { city: "Las-Vegas" },
      { city: "Boston" }
    ]
  },
  {
    "domain2.com": [
      { city: "Miami" },
      { city: "Las-Vegas" },
      { city: "Boston" }
    ]
  },
  {
    "domain3.com": [
      { city: "New-York" },
      { city: "Miami" },
      { city: "Las-Vegas" },
      { city: "Chicago" }
    ]
  }
];

const cities = {};

data.forEach((domainObject) => {
  const domain = Object.keys(domainObject)[0];
  const currentCities = domainObject[domain];
  currentCities.forEach((cityObject) => {
    const city = cityObject.city;
    if (Array.isArray(cities[city])) {
      cities[city].push(domain);
    } else {
      cities[city] = [domain];
    }
  });
});

const result = [];

Object.entries(cities).map(([key, value]) => {
  result.push({ [key]: value });
});

console.log(result)

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 could be causing my 2D integer array to encounter a segmentation fault when using malloc?

I've been troubleshooting this code, trying to understand why it doesn't segfault range(int **range, int min, int max) //prototype *range = (int *)malloc(sizeof(int) * (max - min)); if (*range == NULL) return (0); while (min < max) { ...

AnimationHandler does not animate the Three.js Mesh

I've been struggling to animate the exported mesh from my blender. Even the included buffalo mesh that I see animated in the example is not working for me. I've been attempting to replicate it without success. Here's the code, and I think th ...

The value of the cookie is not set (version 2.0.6 of react-cookie)

I am encountering an issue with implementing react cookies version 2. I am using webpack-dev-server for testing. Below is the console log: Warning: Failed context type: The context cookies is marked as required in withCookies(App), but its value is unde ...

Exploring the complexities of working with arrays of diverse objects in Swift

Hey there, I have a quick question about Swift syntax as a beginner... I'm trying to work with a 2D array of UIImageView objects in my code but I keep running into this error: Cannot subscript a value of type [[UIImageView]] with an index of typ ...

Tips for creating a dynamic menu item that stands out with a highlighted style

I would like to add a colored square to highlight the active menu item. .main-menu ul { padding: 0; margin: 0; text-align: center; } .main-menu li { list-style-type: none; display: inline-block; padding: 40px 0; } .main-menu a { font-fam ...

What is the best way to update my real-time search results by clicking on the clear button inside the search input field using JavaScript?

I’ve been working on implementing a live search feature. I managed to create live search using ajax, so it displays results that match the alphabet or word I type in. However, I encountered an issue with the cross button inside the search field. When cli ...

Can a key event be activated on the DOM Window using Javascript or JQuery?

Can a key event be triggered on the DOMWindow or DOMDocument using JavaScript? I am developing a browser extension to interact with a website that has shortcut key events, similar to those in GMail. While I have come across other methods for triggering key ...

Transmitting PHP variable to JavaScript using Callback Method

I am looking to implement password validation using JavaScript along with an Ajax function. Upon successful validation, I aim to return a boolean variable (true or false) and perform specific actions in my PHP file based on the callback. Unfortunately, my ...

Using a variety of layouts with express-ejs-layout

My current project utilizes express-ejs-layout for routing. I am looking to implement different layouts based on the query parameters. For instance, if the query is: www.example.test/a, I want to use LayoutA.ejs; and if the query is: www.example.test/b, I ...

Activate Button upon Textbox/Combobox/RadDatePicker Modification through JavaScript

On my ASP.NET form, I have various input elements including textboxes, dropdowns, date pickers, and update buttons. My goal is to enable the update button whenever a user makes a change in any of these fields. To achieve this, I applied a specific CSS cla ...

How do I go about developing a function in processing that can identify the maximum value in a given array?

Looking to create a function that can identify the maximum value in the volume array and return the corresponding note from the note array. Furthermore, I am interested in finding a way to adjust it so that only the loudest note is played. import arb.sou ...

Is it possible to utilize JavaScript on a mobile website for item counting purposes?

I have a task at hand that I need help with, and I'm unsure of the best approach to take. The goal is to create a mobile web page that can count items during a specific session. There will be four different items that need to be counted: chicken, cow, ...

Leveraging the Scroll feature in Bootstrap for smooth scrolling

Seeking assistance with implementing scroll in Bootstrap 5 on my child component (ProductList.vue). Can anyone guide me on how to integrate the code? I have been searching for a solution without success. Below is the Bootstrap 5 code on the child component ...

Issue with simulating keydown events in Material UI Popover

Is it possible to navigate a dropdown list using arrow keys instead of TAB/TAB+SHIFT? One idea is to replace the arrow key events with simulated TAB/TAB+SHIFT key events. My approach involves the code below, which successfully prevents default arrow key ev ...

Is it possible to utilize the Node.JS PassThrough stream as a straightforward input buffer?

In my Node.js application, I am utilizing a subprocess referred to as the "generator" to produce data. The challenge arises when the generator occasionally outputs a large chunk of data at a speed of around 50MB/s, while generally operating at a much slowe ...

AngularJS - the element of surprise in execution sequence

Encountering a puzzling issue that exclusively affects Internet Explorer (any version) and not Chrome. An "items" array is stored within the "doc" object. Users have the capability to edit items, which essentially deletes the item but retains its content ...

Can you suggest a method using Lodash to remove specific rows from an array based on the value of a certain field within the array?

Currently, I am utilizing the following function: remove: function (arr, property, num) { for (var i in arr) { if (arr[i][property] == num) arr.splice(i, 1); } }, Although this functi ...

Accessing External Sites Remotely: A Guide to Logging in with Wix

I currently have a Wix website along with a customer portal hosted on a separate platform. My goal is for customers to seamlessly log in to my website and be redirected straight to the customer portal without encountering an additional login screen. Behin ...

ReactJS does not update the conditional CSS class when hovering with mouseOnEnter or mouseOnOver

I am currently attempting to showcase data in a table where each row features an info icon that is only visible upon hovering. Additionally, I want a pop-up to appear when the info icon is clicked (there is an onclick function assigned to this button). He ...

Is array.push not functioning properly?

let teamMembers = []; response.team.members.forEach(async m => { let userResponse; try { userResponse = await axios.get(`https://api.hypixel.net/player?key=KEY&uuid=${m.uuid}`); } catch (err) { console.error(err); } ...