Romain Le Qllc
Romain Le Qllc

Reputation: 896

Merge 2 arrays of objects setting key from one and value from the other

I have 2 objets a and b defined as the following :

a = {
  1:3,
  2:5,
  3:1,
}

b = {
  1:{name:"Bob"},
  2:{name:"John"},
  3:{name:"Alice"}
}

What I am trying to get is the following object c defined as

c = {
  "Bob":3,
  "John":5,
  "Alice":1
}

So creating an using b[key].name as c[key] and a[key] as value.

What I tried so far is

const mapAandB = (a, b) => {
  let finalObject = [];
  Object.keys(b).forEach(key => {
    return finalOdds.push({ [b[key].name]: a[key] });
  });
  return finalOdds;
};

but then the result is

c = [
  0:{Bob:3}, 
  1:{John: 5}, 
  2:{Alice:1}
]

If you have any suggestion ...

Upvotes: 0

Views: 65

Answers (2)

Suren Srapyan
Suren Srapyan

Reputation: 68635

Try this solution. If you want to get an object instead of array, just add the result into the Object.assign(...result)

const a = {
  1:3,
  2:5,
  3:1,
}

const b = {
  1:{name:"Bob"},
  2:{name:"John"},
  3:{name:"Alice"}
}

const mapAandB = (a, b) => Object.keys(a).map(key => ({[b[key].name]: a[key]}));

console.log(mapAandB(a,b));

Upvotes: 1

Ori Drori
Ori Drori

Reputation: 191916

You can use Array#reduce to collect the names and values into an object:

const a = {"1":3,"2":5,"3":1}

const b = {"1":{"name":"Bob"},"2":{"name":"John"},"3":{"name":"Alice"}}

const result = Object.keys(a).reduce((r, key) => {
  r[b[key].name] = a[key];
  
  return r;
}, {});

console.log(result);

Or you can use Array#map to create a series of objects, and combine them to one using Object#assign and spread:

const a = {"1":3,"2":5,"3":1}

const b = {"1":{"name":"Bob"},"2":{"name":"John"},"3":{"name":"Alice"}}

const result = Object.assign(...Object.keys(a).map((key) => ({ [b[key].name]: a[key] })));

console.log(result);

Upvotes: 5

Related Questions