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?

5
  • 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 on one, and resolving the keys on the other should let you write the code you need. Commented Jan 30, 2023 at 18:12
  • So you want to zip them together. Commented Jan 30, 2023 at 18:18
  • Step 1, Step 2. const letterArray = Object.assign([], letters), numberArray = Object.assign([], numbers), result = Object.fromEntries(letterArray.map((letter, index) => [ letter, numberArray[index] ]));. Commented Jan 30, 2023 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])); Commented Jan 30, 2023 at 18:19
  • If these are actually objects, not arrays: Object.entries(letters).reduce((acc, [k,v]) => ({...acc, [v]: numbers[k]}), {}); Commented Jan 30, 2023 at 18:20

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.