wyc
wyc

Reputation: 55273

How to assign the result of a _.each loop to a variable?

The following code creates a Document. Once that's finished it searches for all the documents and push them into a list called this.documents:

store.create(document).then(() => {
  store.find().then((results) => {
    this.documents = []
    _.each(results, (result) => {
      this.documents.push(result.toJSON())
    })
  })
})

It works fine. But I thought that, instead of pushing the items into a list, I could directly assign the _.each loop into a variable:

store.create(document).then(() => {
  store.find().then((results) => {
    this.documents = _.each(results, (result) => {
      return result.toJSON()
    })
    console.log(this.documents)
  })
})

console.log(this.documents), though doesn't output the individual items but this:

[ParseObjectSubclass, ParseObjectSubclass, ParseObjectSubclass, ParseObjectSubclass, ParseObjectSubclass, ParseObjectSubclass, ParseObjectSubclass, ParseObjectSubclass, ParseObjectSubclass, ParseObjectSubclass]

What's the correct way of doing what I want to accomplish?

Upvotes: 0

Views: 78

Answers (1)

Daniel A. White
Daniel A. White

Reputation: 190915

I think you want _.map instead of _.each.

Upvotes: 3

Related Questions