Home > Mobile >  How can I invert array and object to a different outcome in JavaScript?
How can I invert array and object to a different outcome in JavaScript?

Time:11-05

For a project of my own I need something I've never done before. I have data from a database like this:

{
  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" },
  ]
}

So an object with a domain name and in it an array with city names

Is it possible to turn this around, so get a list with city and the associated domain names? For example, like this:

{
  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" },
  ]
},

CodePudding user response:

The other comments may help with explaining. I came up with this quick solution

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)

If this helps, please accept this answer or 1 it. I'am trying to get some reputation points to be able to upvote solution on this website :)

  • Related