[Solved] Dynamically build JS object from collection and pass to AutoForm

Hello,

I’m trying to get a list of user emails into a variable so i can use with an autoForm. This is really easy to do with templates, but i want it in the JS so i can pass cleanly to an autoForm.

userOptions: function() {

let users = Meteor.users.find({}, { fields: { "emails.address": 1 } });
for (let i=0; i < users.count(); i++) {
	console.log(users[i]._id); //this does not work obviously
}

return { //I want to return the id and email like below, the email being the label and the id being the value. 
  2013: "2013",
  2014: "2014",
  2015: "2015"
};

Been trying to get this to work for a bit. Just need another pair of eyes to look at it. Please and thank you.

Edit: The plan is to use JSON.stringify once i had the data, but not got there yet.

Tat

Hi,

So this is what I am trying to do, which is also being silly.

userOptions: function() {
let users = Meteor.users.find({}, { fields: { “emails.address”: 1 } });

let output1 = users.map(user => user._id);
let output2 = users.map(user => user.emails[0].address);
let output3 = null;

//users.map(user =>  console.log(user._id + ':"' + user.emails[0].address+'"')); 

for (let i=0; i < users.count(); i++) {
	output3 += output1[i]+':'+output2[i]+',';
}
return output3;
//return {
//  2013: "2013",
//  2014: "2014",
//  2015: "2015"
//};

}

There has got to be an easier way to do this right? Cause the manual attempt at building JSON is clearly not working.

Tat

Ok,

Made some more progress. Now code looks like -

userOptions: function() {
let users = Meteor.users.find({}, { fields: { “emails.address”: 1 } });

let output1 = users.map(user => user._id);
let output2 = users.map(user => user.emails[0].address);
let output3 = {};

for (let i=0; i < users.count(); i++) {
	output3[output1[i]] += output2[i];
}

console.log(output3);

return output3;

}

The problem is I’m getting some random undefined field in there.

Object {r5t8aQuKKXRrQYEbk: “undefinedtest1@test.com”, oyxBoiRYojNdEwEcZ: “undefinedtest2@test.com”, C52bs2QPEBAYw4DFR: “undefinedtest3@test.com”}

Which is really close to what i need. Why is the undefined showing up at the start of the email addresses?

Tat

Solved.

for (let i=0; i < users.count(); i++) {
output3[output1[i]] = output2[i];
}

Can’t believe it took me so long.

Tat

Why not a bit shorter?

var users = Meteor.users.find().fetch()

var output = users.reduce(function(output, user) {
  output[user._id] = user.emails[0].address
  return output
}, {})

hey,

your way works much better. I’m new to JS, so was wondering if you could clarify something for me.

what does the ‘, {}’ at the end of the users.reduce do? I understand that you are doing a .reduce on the output of the inner function.

Thanks so much.

Tat

That’s the initial value to use: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

thanks so much, help is very much appreciated. I’ll have a look.