首页 > 解决方案 > 通过键合并对象并创建新的键名

问题描述

我有 2 个对象数据。

let continent = {
  "BD": "AS",
  "BE": "EU",
  "BF": "AF",
  "BG": "EU"
}

let capital = {
  "BD": "Dhaka",
  "BE": "Brussels",
  "BF": "Ouagadougou",
  "BG": "Sofia"
}

我想像这样合并它

{
  "BD": {
    "continent": "AS",
    "capital": "Dhaka",
  },
  "BE": {
    "continent": "EU",
    "capital": "Brussels",
  },
  "BF": {
    "continent": "AF",
    "capital": "Ouagadougou",
  },
  "BG": {
    "continent": "EU",
    "capital": "Sofia",
  }
}

我不知道如何实现它。

先感谢您。

标签: javascriptobject

解决方案


您可以与以下函数合并,只需确保以与对象相同的顺序传递键名。您可以使用以下方法合并任意数量的对象。

let continent = {
  "BD": "AS",
  "BE": "EU",
  "BF": "AF",
  "BG": "EU"
};

let capital = {
  "BD": "Dhaka",
  "BE": "Brussels",
  "BF": "Ouagadougou",
  "BG": "Sofia"
};

function merge() {
  const args = Array.from(arguments);
  const keys = args.filter(e => 'string' === typeof e);
  const objs = args.filter(e => 'object' === typeof e);
  return objs.reduce((a, b, i) => {
    Object.entries(b).forEach(([key, value]) => {
      if (! a[key]) {
        a[key] = {[keys[i]]: value}
      } else {
        a[key][keys[i]] = value;
      }
    });
    return a;
  }, {})
}

console.log(merge('continent', 'capital', continent, capital));

不用过滤可能更容易使用arguments

function merge(keys, objects) {
  return objects.reduce((a, b, i) => {
    Object.entries(b).forEach(([key, value]) => {
      if (! a[key]) {
        a[key] = {[keys[i]]: value}
      } else {
        a[key][keys[i]] = value;
      }
    });
    return a;
  }, {})
}

console.log(merge(['continent', 'capital'], [continent, capital]));

要省略编写每个键,您还可以将参数作为对象数组传递,如下所示。这需要将变量命名为所需的键。

function merge(data) {
  return data.reduce((a, b, i) => {
    const key = Object.keys(b)[0];
    Object.entries(b[key]).forEach(([k, v]) => {
      if (!a[k]) {
        a[k] = {[key]: v}
      } else {
        a[k][key] = v;
      }
    });
    return a;
  }, {})
}
console.log(merge([{continent}, {capital}]));

推荐阅读