Get Collection Object with Only One Field

Hey guys,

I am using a package that requires data to come as an object like this:

data = {
  "Name1": null,
  "Name2": null
}

In my app, Names are inside a collection. I would like to know how to get data from this collection and transform it to the format above.

I tried this:
Collection.find({},{fields:{name:1}}).fetch();

But don’t know how to transform the resulting array to an object with the structure shown above… The result is:

[
   0: {name: "TestName 1", _id: "wN3p7F36jcG3Bm9jE"}
   1: {name: "TestName 2", _id: "6Gyog8Wicf9uxqFAy"}
   2: {name: "TestName 3", _id: "s6C2FC8rxjqRdo6G5"}
]

Any ideas?

Thanks!

You can use reduce to iterate over each item and turn the name into a key:

const list =  Collection.find({},{fields:{name:1}}).fetch();

const listObject = list.reduce((acc, curr) => {acc[curr.name] = null; return acc}, {});
1 Like