To build on @rcsole's great answer, this works well:
states = [{
state: "NY",
name: "New York",
}, {
state: "AZ",
name: "Arizona",
}]
statesObj = Object.assign({}, ...states.map(state => {
return { [state.state]: state.name }
}))
Result:
{
AZ: "Arizona",
NY: "New York",
}
What's going on here?
Let's break this up into multiple pieces:
// Step 1: Transform from [{state: "Foo", name: "Bar"}, ...] to [{Foo: "Bar"}, ...]
mappedStates = states.map(state => { return { [state.state]: state.name } })
// Step 2: Merge all the objects in that array into a single new object
statesObj = Object.assign({}, ...mappedStates)
Step 1 uses map
to iterate over every item in the array (every state object). map
executes a function for every state
object and returns a new object with the state as the key and the name as the value. We need to surround state.state
in brackets because it's a dynamic value in an object literal.
Step 2 uses Object.assign
to merge all the new state objects in the mappedStates
array into a new object (the first parameter, {}
).
What are the three dots ...
for? That's the spread operator. It takes every element in the mappedStates
array and turns them into direct arguments of the Object.assign
method.
This example makes it clear:
Object.assign({}, ...mappedStates)
is the same as
Object.assign({}, {AZ: "Arizona"}, {NY: "New York"})
That's it!