kyun
kyun

Reputation: 10274

merge objects by key and create new key name

I have 2 object data.

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

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

I want to merge it like this

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

I have no idea how to achieve it.

thank you in advance.

Upvotes: 1

Views: 47

Answers (2)

Code Maniac
Code Maniac

Reputation: 37755

You can use Object.entries and 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)

Upvotes: 1

baao
baao

Reputation: 73251

You can merge with below function, just make sure to pass the key names in the same order as the objects. You could merge any number of objects with below method.

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

Maybe easier to use without filtering 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]));

To omit having to write every key, you can also pass the arguments as an array of objects like below. This requires the variables be named as the desired keys though.

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

Upvotes: 2

Related Questions