How to convert an array of objects to an object in Lodash?
Asked Answered
B

6

20

I have this:

[ 
  { list: [ [Object], [Object] ] },
  { head: [ [Object], [Object] ] }
]

And want to turn it into this:

{ 
  list: [ [Object], [Object] ],
  head: [ [Object], [Object] ]
}

So an array of objects into an object. It would be great to achieve this with lodash.

Boehm answered 13/5, 2015 at 17:12 Comment(1)
I don't know anything about Java or lodash, but if you've done any research, it can really help if you share that, too! ;)Lishalishe
G
23
_.reduce(array, function(memo, current) { return _.assign(memo, current) },  {})
Gauze answered 13/5, 2015 at 17:22 Comment(0)
A
28

I think an even shorter solution would be:

Object.assign({}, ...array)

I know you asked for lodash, but it doesn't seem like you even need this way. Unless you want to use _.extend.

Amorino answered 18/4, 2016 at 11:1 Comment(4)
Perhaps my js is broken - but this just gets me the last element as an object. This however had interesting result: Object.assign({}, ... rows.map(x=>{return {[x.name]:false}}) ); Which is the same belowNashville
Hey @terary, can you share what your object looks like?Amorino
{"list":[{"some":"object1"},{"some":"object2"}],"head":[{"some":"object3"},{"some":"object4"}]} Node v12.19Nashville
Sorry, I guess I should've asked what does your original array look like? Or is the list property that you're trying to transform?Amorino
G
23
_.reduce(array, function(memo, current) { return _.assign(memo, current) },  {})
Gauze answered 13/5, 2015 at 17:22 Comment(0)
A
11

Here's a shorter version:

_.transform(array, _.ary(_.extend, 2),  {});

The transform() function is like reduce(), except it's not expecting you to return anything. Since extend() is altering it's first argument, we can just pass it straight to transform(). It's wrapped in ary() to make sure it only gets 2 arguments passed to it.

Anachronistic answered 13/5, 2015 at 21:4 Comment(0)
E
10

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!

Ear answered 28/12, 2017 at 19:33 Comment(1)
Thanks for showing the use of square brackets creating object properties by namePilkington
M
1

Use fromPairs on lodash 4. https://lodash.com/docs#fromPairs

_.fromPairs([['fred', 30], ['barney', 40]]);

Melanoid answered 25/4, 2016 at 9:1 Comment(0)
M
0

With TypeScript:

interface State {
  state: string;
  name: string;
}

const states: State[] = [
  { state: "NY", name: "New York" },
  { state: "AZ", name: "Arizona" },
];

const statesObj = reduce<State, Record<string, string>>(
  states,
  (memo, { state, name }) => assign(memo, { [state]: name }),
  {},
);

console.log(statesObj); // <-- {AZ: "Arizona"}, {NY: "New York"}
Monreal answered 14/5 at 18:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.