homerboy homerboy -4 years ago 135
Javascript Question

underscore.js _.where for string and objects

I want to check if a string can be found in a list of objects.

has a string "apple, peach" and
is a list of object, where each object has a key-value pair. I want to see if "apple, peach" is found in

From the documentation on Underscore.js:
_.where(list, properties)
and I don't think I can input a string as
. How can I check if a string is found in a list of objects?

render() {
fruits = this.props.value # "apple, peach"
newFruits = _.where(this.props.value, this.state.list) # I want to see if "apple, peach" is found in the list of fruits in state, and if so, re-assign those values into newFruits

return (

Answer Source

It's not clear what you want. If you want a list of objects (key value pair) that shows up in the list, you probably should do the following:

newFruits = _.filter(this.state.list, o => _.contains(this.props.value, o.name))

Otherwise, if you just want a list of the fruits, you can do the following:

newFruits = _.intersect(this.props.value, _.pluck(this.state.list, 'name'))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download