DR01D
DR01D

Reputation: 1365

How to us reduce() to build an object without cycling through multiple iterations

I'm experimenting with .reduce() by building objects.

The code below successfully builds the object but it's wasteful. .reduce() cycles through its loop 3 times because the array contains 3 items. But the way I assign the keys and values .reduce() only needs to cycle through once. Is there a way to make .reduce() cycle just once or alternately is there a more efficient way to approach this problem? Thanks for any input!

"use strict";

var creatureArray = [];
var creatureObject = {}

creatureArray = ["Skeleton", "Sword", 10];

creatureObject = creatureArray.reduce((accumulator, currentValue, index, array) => {
    accumulator[array[0]] = {
        weapon: array[1],
        damage: array[2]
    }
    return accumulator;
}, {});

console.log(creatureObject);

Upvotes: 0

Views: 24

Answers (1)

user8897421
user8897421

Reputation:

Not sure why you'd want to use .reduce() at all here. You seem to be anticipating the array having only those three items, so just assign them.

"use strict";

var creatureArray = ["Skeleton", "Sword", 10];

var creatureObject = {
    [creatureArray[0]]: {
        weapon: creatureArray[1],
        damage: creatureArray[2]
    }
}

console.log(creatureObject);

Upvotes: 2

Related Questions