homerboy homerboy - 3 months ago 8
Javascript Question

underscore.js _.where for string and objects

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

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

From the documentation on Underscore.js:
_.where(list, properties)
and I don't think I can input a string as
list
. 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 (
<div>
<p>{newFruits}</p>
</div>
)
}

Answer

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'))