Dimisizz
Dimisizz

Reputation: 69

Convert two arrays to an object

I have the lists of fathers and children:

const fathers = [
    'Bob',
    'John',
    'Ken',
    'Steve'
];

const children = [
    [ 'Mike', 'David', 'Emma' ],
    [],
    [ 'Harry' ],
    [ 'Alice', 'Jennifer' ]
];

How can I convert them to an object like this:

const relation = {
    Bob: [ 'Mike', 'David', 'Emma' ],
    John: [],
    Ken: [ 'Harry' ],
    Steve: [ 'Alice', 'Jennifer' ]
};

Upvotes: 0

Views: 60

Answers (3)

IsraGab
IsraGab

Reputation: 5175

2 solutions:

First one is to declare an empty object and run over each parent with a loop.

Second one is to use a reducer

var fathers = [
    'Bob',
    'John',
    'Ken',
    'Steve'
];

var children = [
    [ 'Mike', 'David', 'Emma' ],
    [],
    [ 'Harry' ],
    [ 'Alice', 'Jennifer' ]
];

// option 1
  var relations = {};
  fathers.forEach((father, idx) => relations[father] = children[idx])

  console.log(relations);


// option 2
  var relations2 = fathers.reduce((acc, father, idx) => {
      acc[father] = children[idx];
      return acc;
}, {}
)
  console.log(relations2 );

Upvotes: 2

Derek Wang
Derek Wang

Reputation: 10193

Using Array.prototype.reduce, you can convert them into the object as follows.

const fathers = [
    'Bob',
    'John',
    'Ken',
    'Steve'
];

const children = [
    [ 'Mike', 'David', 'Emma' ],
    [],
    [ 'Harry' ],
    [ 'Alice', 'Jennifer' ]
];

const output = fathers.reduce((acc, curV, curI) => ({ ...acc, [curV]: children[curI] }), {});
console.log(output);

Upvotes: 4

michael
michael

Reputation: 4173

const fathers = ['Bob', 'John', 'Ken', 'Steve'];

const children = [
  ['Mike', 'David', 'Emma'],
  [],
  ['Harry'],
  ['Alice', 'Jennifer']
];

const relation = {};
fathers.forEach((item, index) => {
  relation[item] = children[index];
});
console.log(relation);

Upvotes: 3

Related Questions