Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert array to object in JavaScript

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.

like image 332
lexicore Avatar asked Aug 16 '26 13:08

lexicore


1 Answers

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);
like image 188
Nina Scholz Avatar answered Aug 19 '26 03:08

Nina Scholz



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!