Join the Stack Overflow Community
Stack Overflow is a community of 6.6 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I'd like to convert an array into an object using one of the properties as key.

For instance:

var stations = [ { name: 'A Coruna', ds100: 'OECSC' }, ... ];

I'd like to get stationByDs100:

{ 'OECSC': { name: 'A Coruna', ds100: 'OECSC' }, ... }

At the moment I do it as follows:

var stationByDs100 = {};
stations.forEach(station => stationByDs100[station.ds100] = station);

I'm looking for a better way to accomplish this - is it possible with a one-liner without explicit variable declaration?

For instance in Java 8 this could have accomplished with streams and collectors in one line like:

Map<String, Station> stationByDs100 = stations.stream()
    .collect(toMap(Station::getDs100, identity()));

So I was thinking maybe there's a similar way in JS.

I'm using Node.js so OK to use the latest JS/ES features Node.js supports.

I've browsed through a rougly dozen existing answers but they mostly use older JS/ES versions and suggest even longer solutions.

share|improve this question
1  
Use Array.prototype.reduce, see MDN for examples. – RobG 30 mins ago
    
@SpencerWieczorek One-liner, without explicit variable declaration, from said criteria it is better. – lexicore 24 mins ago
    
Is there a specific purpose for wanting the code to be a one-liner? Usually one-line code, especially involving functional-style array methods, are slower than the equivalent code using for/while loops and more than one line of code – Zorgatone 22 mins ago
1  
@Zorgatone No technical reason. I don't care about performance in this case and wanted to learn more about functional style in JS as I'm quite weak in that. – lexicore 20 mins ago
    
Ok, makes sense – Zorgatone 19 mins ago
up vote 6 down vote accepted

You could use Object.assign with computed property names.

var stations = [ { name: 'A Coruna', ds100: 'OECSC' }],
    object = stations.reduce((o, a) => Object.assign(o, { [a.ds100]: a }), {});

console.log(object);

share|improve this answer
    
I would prefer Object.assign({}, o, { [a.ds100]: a }) instead of Object.assign(o, { [a.ds100]: a }) to prevent side effects. just a personally preference. – NonPolynomial 18 mins ago
    
the difference is, i return the same object, while NonPolynomial suggest to use a new object all time. – Nina Scholz 15 mins ago
    
@NinaScholz Yes, I got it, thank you. I think it's not really necessary in this case as accumulator object is only used in reduction. – lexicore 7 mins ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.