Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript, reduce. Need function that makes array to object

Reduce method is not easy, help me with this problem pls.

i need a function, that receive array with anything, and returns object with fields

{field1, field2, field3, field4}

like in the example: Input:

[true,6,'wow','you are smart, bro']

Output:

{field1: true, field2:1, field3: 'wow', field4: 'you are smart, bro'}

like image 474
Identicon Avatar asked Sep 14 '26 04:09

Identicon


1 Answers

A solution that uses Object.fromEntries (browsers that support ECMAScript 2019 only):

const arr = [true, 6, 'wow', 'you are smart, bro'];

const result = Object.fromEntries(arr.map((x, i) => [`field${i + 1}`, x]));

console.log(result);

A solution that uses Array.prototype.reduce and ECMAScript 2015:

const arr = [true, 6, 'wow', 'you are smart, bro'];

const result = arr.reduce((acc, cur, i) => ({ ...acc, [(`field${i + 1}`)]: cur }), {});

console.log(result);

And a solution that uses Array.prototype.reduce and ECMAScript 5 (browsers as old as IE11):

var arr = [true, 6, 'wow', 'you are smart, bro'];

var result = arr.reduce(function(acc, cur, i) {
    acc['field' + (i + 1)] = cur;
    return acc;
}, {});

console.log(result);
like image 130
Guerric P Avatar answered Sep 16 '26 16:09

Guerric P



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!