按键合并对象并创建新的键名

问题描述 投票:1回答:2

我有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",
  }
}

我不知道如何实现它。

先感谢您。

javascript object
2个回答
2
投票

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

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}]));

1
投票

您可以使用Object.entries和map

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

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


let op = Object.entries(continent).map(([key,continent])=>(
 { [key] :{
           continent,
           capital:capital[key]
          }
}))

console.log(op)
© www.soinside.com 2019 - 2024. All rights reserved.