0

I discovered many asked questions like this. Unfortunately couldn't find the right solution. If this question is duplicated, please be gentle and let me know.

Describe the issue: I have two objects like below:

const letters = {
  0: "A",
  1: "B",
  2: "C",
  3: "D"
};

const numbers = {
  0: 47,
  1: 48,
  2: 37,
  3: 29
};

I want to merge them like keys and values:

let result = {
  A: 47,
  B: 48,
  C: 37,
  D: 29
};

Is it available to achieve that with shorter ways?

BB.
  • 169
  • 1
  • 12
  • 2
    Are you sure those are objects and not just arrays? Because if they're arrays, just iterating over them will work just fine. If they're actual objects, using [Object.entries](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries) on one, and resolving the keys on the other should let you write the code you need. – Mike 'Pomax' Kamermans Jan 30 '23 at 18:12
  • So you want to *zip* them together. – Fractalism Jan 30 '23 at 18:18
  • [Step 1](/a/57221894/4642212), [Step 2](/q/1117916/4642212). `const letterArray = Object.assign([], letters), numberArray = Object.assign([], numbers), result = Object.fromEntries(letterArray.map((letter, index) => [ letter, numberArray[index] ]));`. – Sebastian Simon Jan 30 '23 at 18:19
  • You can transpose the two arrays and convert the entries to an object: `transpose = (matrix) => matrix[0].map((_, colIndex) => matrix.map(row => row[colIndex])), letters = ['A', 'B', 'C', 'D'], numbers = [47, 48, 37, 29], result = Object.fromEntries(transpose([letters, numbers]));` – Mr. Polywhirl Jan 30 '23 at 18:19
  • If these are actually objects, not arrays: `Object.entries(letters).reduce((acc, [k,v]) => ({...acc, [v]: numbers[k]}), {});` – Tom Jan 30 '23 at 18:20

0 Answers0