-1

I can achieve this using the for loop but I cant figure out how to use forEach to do the same.

for example: var input = [['make', 'Ford'], ['model', 'Mustang'], ['year', 1964]]; calling the function should result in:

{
  make : 'Ford',
  model : 'Mustang',
  year : 1964
}
3
  • Why are you limited to forEach? Commented Apr 1, 2021 at 16:40
  • Convert Array to Object is the canonical duplicate. If your answer is the same as the answers there (i.e., uses reduce) DO NOT ANSWER THIS QUESTION. This question asks about using forEach. Commented Apr 1, 2021 at 16:46
  • 1
    Call Object.fromEntries() with the array as parameter. Commented Apr 1, 2021 at 16:46

2 Answers 2

1

We can achieve this using forEach and Array destructuring

var input = [
  ["make", "Ford"],
  ["model", "Mustang"],
  ["year", 1964],
];

const result = {};

input.forEach(([prop, value]) => {
  result[prop] = value;
});

/*--------- OR --(withour array destructuring)-------------
input.forEach(internalArr => {
  result[internalArr[0]] = internalArr[1];
});
*/

console.log(result);

You can also achieve this using Array.prototype.reduce. Array.prototype.reduce is the right tool to do this job.

var input = [
  ["make", "Ford"],
  ["model", "Mustang"],
  ["year", 1964],
];

const result = input.reduce((acc, curr) => {
  const [prop, value] = curr;
  acc[prop] = value;
  return acc;
}, {});

console.log(result);

Sign up to request clarification or add additional context in comments.

9 Comments

We have many duplicates of "better options" using reduce among others solutions. This question asks for answers using forEach.
@HereticMonkey added the solution with forEach also
I'd say Array.prototype.reduce is not the right tool. It doesn't differ from other loop construct, really.
@appleapple I'd love if you can explain me, why Array.prototype.reduce is not the right tool. May be there is something that I don't know. So that I can learn something new from you. ☺☺☺
@DeC it's why I highlight the. I just mean it doesn't have real benefit over other loop construct.
|
0

You could take a closure for the target object and iterate the array with the returned function from convert.

const
    convert = target => ([key, value]) => target[key] = value,
    input = [['make', 'Ford'], ['model', 'Mustang'], ['year', 1964]],
    output = {};

input.forEach(convert(output));

console.log(output);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.