Aayush Chadha Aayush Chadha - 1 month ago 7
Node.js Question

How do I create a new object if the condition is true?

I want to add the values associated with the arrayOpportunityCategory(An array containing comma separated strings and is part of a JSON object) to a new object/array if a user inputted value is in arrayOpportunityCategory.

So far, I have this:

const category = _.forOwn(res.body, function(val, key){
const arrayOpportunityCategory = val.category.split(" ")
if(arrayOpportunityCategory.indexOf(interest.raw) > -1){
const suggestedOpportunity = []
suggestedOpportunity.push(val)
} else {
console.log('Sorry, we have nothing of that sort.')
}
})

}

Answer
const suggestedOpportunity = []
const category = _.forOwn(res.body, function(val, key){
      const arrayOpportunityCategory = val.category.split(" ")
      if(arrayOpportunityCategory.indexOf(interest.raw) > -1){    
        suggestedOpportunity.push(val)
      } else {
        console.log('Sorry, we have nothing of that sort.')
      }
    })    
  }

Declare your suggestedOpprtunity array outside of your loop, else you would end up having creating a new array for each iteration and finally you would have only the last values.