atmd
atmd

Reputation: 7490

is there an elegant way to add key/value to an object from an array

As part of a angular2/typescript project I have an array of objects. The objects contain a set of key/value pairs that come from a database. That then gets mapped to a table on the ui side (using ag-grid-ng2).

The headers for the table are dynamic and set in the DB.

one task I have is to map an array of key/values to a single object, like this:

const things = [
  {
    field: 'some_table_header', 
    humanReadable: 'Some table header'
  }
];

turns into:

const anObjectFullOfThings = {
  some_table_header: 'Some table header'
};

I currently feel my code could be much more elegant and concise, i.e.:

let anObjectFullOfThings = {};

things.forEach((thing) => {
  anObjectFullOfThings[thing.field] = thing.humanReadable;
});

I feel there must be something better, i.e. to go the other way i'd map over Object.keys etc. Is there an alternative way to map an array to object keys?

Upvotes: 0

Views: 368

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075755

What you have is just fine.

Some people would use reduce:

let anObjectFullOfThings = things.reduce((obj, thing) => {
    obj[thing.field] = thing.humanReadable;
    return obj;
}, {});

...but it's a matter of taste, particularly as the reduce isn't really reducing anything, it's just perpetuating the same object throughout the loop.

Upvotes: 2

Related Questions