最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

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

matteradmin10PV0评论

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"

Articles related to this article

Post a comment

comment list (0)

  1. No comments so far