skip to Main Content

I had two array:

const keys = [a, b, c]
const values = [[], [], []]

I want to convert it to a 2d array:

const entries = [[a, []], [b, []], [c, []]]

How can I do it?

P.S. Actually I want to apply Object.fromEntries to initialise an object in the end.

const x = {a: [], b: [], c: []}

3

Answers


  1. You can use an Array.map for example

    const keys = ["a", "b", "c"]
    const values = [[], [], []]
    
    const entries = keys.map((key, i) => [key, values[i]]);
    
    const obj = Object.fromEntries(entries)
    console.log(obj)

    or forEach

    const keys = ["a", "b", "c"]
    const values = [[], [], []]
    
    const obj = {}
    keys.forEach((key,i) => obj[key] = values[i])
    
    console.log(obj)

    or a reduce

    const keys = ["a", "b", "c"]
    const values = [[], [], []]
    
    
    const obj = keys.reduce((acc,cur,i) => (acc[cur] = values[i], acc),{})
    
    console.log(obj)
    Login or Signup to reply.
  2. const data = keys.map((key, index) => [key, values[index]]);

    you can use this data like this : Object.fromEntries(data)

    Login or Signup to reply.
  3. You may consider Array.reduce, to make Object.fromEntries obsolete:

    const [a, b, c] = [`keyA`, `keyB`, `keyC`];
    const values = [[], [], []];
    const combined = [a, b, c].reduce((acc, val, i) => 
      ({...acc, [val]: values[i]}), {});
    console.log(combined);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search