JavaScript, reduce. Need function that makes array to object - Stack Overflow

Reduce method is not easy, help me with this problem pls.i need a function, that receive array with any

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'}

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'}

Share Improve this question edited Jul 31, 2020 at 14:11 Guerric P 31.8k6 gold badges58 silver badges105 bronze badges asked Mar 14, 2020 at 22:56 IdenticonIdenticon 211 bronze badge 1
  • can you line out what you've tried already ? – monofone Commented Mar 14, 2020 at 23:02
Add a ment  | 

5 Answers 5

Reset to default 7

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);

Solution

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

const f = (acc, rec, index) => {
  acc[`field${index + 1}`] = rec //
  return acc
}

const result = arr.reduce(f, {})
console.log(result)

Explanation

I extracted the callback function into f variable for readability's sake.

The callback function expects the following input: accumulator acc to store the results in, the value of the current processed element rec, and index.

const f = (acc, rec, index) => {...}

The index is optional but we need to get array indexes anyway to use them in our resulting object's keys. We know that array's index count starts from 0 and not from 1, so we have to add + 1 to the count to get field1 key instead of field0.

I chose to use string interpolation to get the necessary result:

`field${index + 1}`

Then we assign the corresponding array element to the object under the key we've just constructed:

acc[`field${index + 1}`] = rec

The reduce function expects the following input: callback (function f ) and initial value, which here should be an empty object {}, since we need to have an object as result.

reduce(f, {})

Now we create new variable result which will be the output of the reduce function on each element of the array arr:

const result = arr.reduce(f, {})

const arr = [true,6,'wow','you are smart, bro'] 
const obj  = arr.reduce(
  (acc, rec, index) => ({ ...acc, [`field${index + 1}`]: rec }),
  {}
)

console.log(obj) 
You need always remember that index start from 0

const result = [true,6,'wow','you are smart, bro']
.reduce((acc, rec, i) => ({...acc, [`field${i + 1}`]: rec}),{})


console.log(result)

const database = [true, 1, "wow", "you are smart, bro"];

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

console.log(result(database));

1 step:

acc(0 elements) + field{0+1}: true
     |
 accumulator is empty

2 step:

acc(1 element) + field{1+1}: 1
     |
 field1: true

3 step:

acc(2 elements) + field{2+1}: "wow"
     |
 field1: true
 field2: 1

4 step:

acc(3 elements) + field{3+1}: "you are smart, bro"
     |
 field1: true
 field2: 1
 field3: "wow"

end:

 field1: true
 field2: 1
 field3: "wow"
 field4: "you are smart, bro"

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1741896746a4372221.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信