Cypher return structured map

is it possible to return an object of objects (each key containing an object)?

what I want to achieve:

 {
     a1 : { name: "bob", age: 45 }, 
     a2 : { name: "toby", age: 27 }
 }

or

 [
   a1 : { name: "bob", age: 45 }, 
   a2 : { name: "toby", age: 27 }
 ]

my statement:

MATCH (n:User)
WITH n.id AS key, {name:n.name, age:n.age}AS value
RETURN collect({key:value})

You are really really close. I think all you need is apoc.map.fromPairs which takes an array of key value pairs and turns them into a map. For example, if you have data like this:

RETURN apoc.map.fromPairs([ ["a", "b"], ["c", "d"] ])

Then you get:

{
  "a": "b",
  "c": "d"
}

So your "values" are nested maps, but that's no problem. If you change your query to this:

match (n:User) 
with n.id as key, { name: n.name, age: n.age } as value 
return apoc.map.fromPairs(collect([key, value]));

I think you'll get what you want.

Note that you can't do this:

{ key: value }

Because in this case cypher interprets "key" as literally the text key, not as the content of whatever that variable is.

2 Likes