You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中反转域名与城市的映射关系?

如何将域名-城市映射转换为城市-域名映射

输入数据格式

const inputData = [
  {
    "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" },
    ]
  }
];

目标输出格式

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

实现代码

function transformDomainCityMap(input) {
  const result = {};
  
  input.forEach(domainObj => {
    // 提取当前域名(每个对象仅含一个域名键)
    const domain = Object.keys(domainObj)[0];
    const cities = domainObj[domain];
    
    cities.forEach(({ city }) => {
      // 若结果中无该城市键,初始化空数组
      if (!result[city]) {
        result[city] = [];
      }
      // 向对应城市数组添加域名对象
      result[city].push({ domain });
    });
  });
  
  return result;
}

// 调用函数获取转换结果
const transformedData = transformDomainCityMap(inputData);
console.log(transformedData);

代码说明

  • 初始化空对象result存储最终转换结果
  • 遍历输入数组中的每个域名对象,提取域名与对应城市列表
  • 逐个处理城市:若结果对象中无该城市的键则创建空数组,再将当前域名对象加入对应数组
  • 最终返回转换完成的城市-域名映射对象

内容的提问来源于stack exchange,提问作者paultje182

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 16:36:18